Python style specification (Google)

Source: Internet
Author: User
Tags class definition shebang

Let's start with Mark. Website: Goole Official website

Programmers in any language, writing code that conforms to the norm, is the first step in starting a program career.

First, semicolon
Do not add semicolons at the end of the line, and do not use semicolons to place two commands on the same row.
two, line length
No more than 80 characters per line

Exception:

    1. Long Import Module statement
    2. The URL in the comment

Do not use backslashes to join rows.

Python can use this feature by implicitly connecting parentheses, brackets, and lines in braces. If you want, you can add an extra pair of parentheses around the outside of an expression.

Yes:foo_bar (self, width, height, color='black', Design=none, x='foo ' ,             emphasis=none, highlight=0)      if  and  and  ' red ' and ' strong '           ):

If a text string does not fit on one line, you can use parentheses to implement an implicit row join

x = ('Long Long long long long     string')

In the note, if necessary, place the long URL on one line.

Yes: # See details at # http://www.example.com/us/developer/documentation/api/ Content/v2.0/csv_file_name_extension_full_specification.html

No:  # See detailsat     #  http://www.example.com/us/developer/documentation/ Api/content/\     #  v2.0/csv_file_name_extension_full_specification.html
three, parentheses
Ningquewulan using parentheses

Do not use parentheses in a return statement or conditional statement unless it is used to implement a row connection. However, it is possible to use parentheses on either side of the tuple.

Four, indentation
Indent Code with 4 spaces

Never use tab and do not mix tabs and spaces.

For a row connection, you should either align the wrapped element vertically (see the example of the line section), or use a 4-space hanging indent (the first line should not have parameters):

five, empty line
The top-level definition is empty between two lines, the method defines an empty line between
    • There are two empty rows between the top-level definitions, such as functions or class definitions.
    • method definition, the class definition and the first method should be empty lines. In a function or method, there is a blank line in some places if you feel fit.
Six, Space
Use spaces on both sides of punctuation according to standard typographic specifications
    1. Do not have spaces in parentheses.
    2. Do not precede commas, semicolons, and colons with spaces, but should be appended to them (except at the end of the line).
    3. argument list, no spaces should be added before the opening parenthesis of an index or slice.
    4. Add a space on either side of the two-dollar operator, such as assignment (=), Comparison (= =, <,;,! =, <>, <=, >=, in, no in, was, is not), Boolean (and, or, not). As for how to use the space on either side of the arithmetic operator, you need to judge it yourself. But be sure to keep it consistent on both sides.
    5. When ' = ' is used to indicate a keyword parameter or default parameter value, do not use spaces on either side of it.
    6. Do not use spaces to vertically align multiple lines of markup, as this will be a burden on maintenance (for:, #, =, etc.)
Seven, Shebang
Most. py files do not have to be #! As the beginning of the file. According to PEP-394, the main file of the program should start with #!/usr/bin/python2 or #!/usr/bin/python3.

(Translator Note: In Computer science, Shebang (also known as Hashbang) is a string line (#!) consisting of a pound sign and an exclamation mark, which appears in the first two characters of a text file. In cases where there is shebang in the file, The program loader of the Unix-like operating system parses the contents of Shebang, interprets them as interpreter directives, invokes the instruction, and takes the file path containing the shebang as the parameter of the interpreter. For example, a file that starts with instruction #!/bin/sh actually calls the/BIN/SH program when it executes.)

#! is first used to help the kernel find the Python interpreter, but it will be ignored when importing the module. It is therefore necessary to join #! only in documents that are directly executed.

Viii. Notes
Make sure you use the correct style for modules, functions, methods, and inline annotations

Block comments and Line comments

The most need to write comments is the tricky parts of the code. If you have to explain it in the next code review, you should write it now. For complex operations, you should write several lines of comments before their operations begin. For code that is not at a glance, you should add a comment at the end of the line.

For readability, the comment should leave at least 2 spaces in the code.

On the other hand, never describe the code. Suppose the person reading the code knows more about Python than you do, he just doesn't know what your code is going to do .

ninth, Class
If a class does not inherit from another class, it is explicitly inherited from object. The same is true for nested classes.

Inherited from object is for the property (properties) to work properly, and this protects your code from a special potential incompatibility with PEP-3000. This also defines some special methods that implement the object's default semantics, including

__new__ __init__ __delattr__ __getattribute__ __setattr__ __hash__ __repr__  and __str__
10. String
Even if the argument is a string, use the% operator or the format method to format the string. But you can't generalize, you need to judge between + and% well.

Avoid using the + and + = operators in loops to accumulate strings. Because the string is immutable, doing so creates unnecessary temporary objects and results in a two-time rather than linear run time. As an alternative, you can add each substring to the list and then use the connection list after the loop ends .join . (You can also write each substring to a cStringIO.StringIO cache.)

11. Documents and Sockets
At the end of the file and sockets, explicitly close it.
12. Todo Comments
Use TODO comments for temporary code, which is a short-term solution. It's not perfect, but it's good enough.
13. Import Format
Each import should have an exclusive line

The import should always be placed at the top of the file, after the module comments and document strings, before the module global variables and constants. The import should be grouped in the order from most general to least common:

    1. Standard library Import
    2. Third-party library import
    3. application Specifies import

In each grouping, the full package path for each module should be sorted by dictionary order, ignoring case.

14. Statements
Typically each statement should have a single row

However, if the test results and test statements are placed on one line, you can also put them on the same line.

If this is an if statement, you can do so only if there is no else. In particular, never try/except do this, because try and except cannot be placed on the same line.

15. Access Control
In Python, for trivial and less important access functions, you should replace them directly with public variables, which avoids the overhead of additional function calls. When adding more features, you can use attributes to keep the syntax consistent. (Translator note: Attaching importance to encapsulation object-oriented programmers see this may be very objectionable because they have been educated: all member variables must be private! Actually, that's a bit of a hassle. Try to accept pythonic philosophy.
16. Naming
Module_name, Package_name, ClassName, Method_name, Exceptionname, Function_name, Global_var_name, Instance_var_name, Function_parameter_name, Local_var_name.

Names that should be avoided

  1. Single-character names, in addition to counters and iterators.
  2. Hyphen (-) in Package/module name
  3. A name that begins and ends with a double underscore (python reserved, for example __init__)

Naming conventions

  1. The so-called "internal (Internal)" means that only modules are available within the module, or that they are protected or private within the class.
  2. Starting with a single underscore (_) indicates that a module variable or function is protected (not included when using import * from).
  3. An instance variable or method that begins with a double underscore (__) represents a private in-class.
  4. Place related classes and top-level functions in the same module. Unlike Java, there is no need to restrict a module to a class.
  5. Words that begin with a capital letter for the class name (such as capwords, Pascal style), but the module name should be underlined in lowercase (such as lower_with_under.py). Although there are already many existing modules that use a name similar to capwords.py, it is now discouraged because if the module name happens to coincide with the class name, it can be confusing.

Python's father Guido recommended specification

Public
Type Internal
Modules Lower_with_under _lower_with_under
Packages Lower_with_under
Classes Capwords _capwords
Exceptions Capwords
Functions Lower_with_under () _lower_with_under ()
Global/class Constants Caps_with_under _caps_with_under
Global/class Variables Lower_with_under _lower_with_under
Instance Variables Lower_with_under _lower_with_under (Protected) or __lower_with_under (private)
Method Names Lower_with_under () _lower_with_under () (protected) or __lower_with_under (private)
Function/method Parameters Lower_with_under
Local Variables Lower_with_under
17. Main
Even a file that is intended to be used as a script should be imported. And a simple import should not cause the main function of this script (main functionality) to be executed, which is a side effect. The main function should be placed in a main () function.

Python style specification (Google)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.