PEP8 Python Coding specification collation (Python)

Source: Internet
Author: User

Add by Zhj: This is Douban friends finishing PEP8, is a simple version of PEP8, because the original PEP8 content too much, so it is recommended to read this article first, and then see PEP8 Chinese Translation

Original: http://www.douban.com/note/134971609/

Decided to start the Python road, using spare time, for more in-depth study of Python. Programming languages are not art, but work or tools, so it is necessary to organize and follow a set of coding specifications. So this afternoon I made a copy according to Pep 8, and I'll follow this code, and I'll keep updating it.

PEP8 Python Coding Specification

A code orchestration
1 indent. Indentation of 4 spaces (the editor can do this), no tap, no mix of taps and spaces.
2 The maximum length per line is 79, the line break can use backslashes, preferably with parentheses. The newline point is to hit enter after the operator.
There are two empty lines between the 3 class and the top-level function definition, an empty line between the method definitions in the class, and an empty line between the logically unrelated paragraphs in the function;

Two-document orchestration
1 sequence of Module contents: module description and docstring-import-globals&constants-other definitions. The import part, in accordance with the standard, three-party and their own writing in order to discharge, between the empty line.
2 Do not have multiple libraries in an import, such as import OS, SYS is not recommended.
3 If you use the From XX import xx Reference library, you can omit the ' module. ', it is possible to have a naming conflict, it is necessary to use import xx.

Use of three spaces
General principle, avoid unnecessary spaces.
1 do not add spaces before the various closing brackets.
2 Do not add spaces before commas, colons, and semicolons.
Do not add a space before the opening parenthesis of the 3 function. such as func (1).
Do not add a space before the opening parenthesis of the 4 sequence. such as list[2].
5 operators add a space around each other, do not add spaces to align.
6 The function default argument uses the assignment character to omit the space left and right.
7 do not write multiple statements on the same line, although use '; ' allows.
8 If/for/while statement, even if the execution statement has only one sentence, another line must be started.

Four notes
The general principle is that the wrong comment is less than the comment. So when a piece of code changes, the first thing to do is change the comment!
Comments must be in English, preferably a complete sentence, the first letter capitalized, after the sentence to have Terminator, the Terminator followed by two spaces, start the next sentence. If it is a phrase, you can omit the terminator.
1 comments, add comments before a piece of code. Add a space after ' # '. Between paragraphs with a line interval of only ' # '. Like what:
# description:module CONFIG.
#
# Input:none
#
# Output:none
2 lines of comments, add a comment after a sentence of code. Example: x = x + # Increment X
But this approach is used sparingly.
3 Avoid unnecessary annotations.

Five Document description
1 Write docstrings for all common modules, functions, classes, methods, not common, but can write comments (on the next line of Def).
2 If the docstring to be wrapped, refer to the following example, see Pep 257
"" "Return a Foobang

Optional Plotz says to frobnicate the Bizbaz first.

"""

Six naming conventions
The overall principle, the new code must be the following naming style, the existing library encoding as far as possible to maintain style.
1 try to use the lowercase letters ' l ', the uppercase letters ' O ' and other easily confusing letters.
2 The module is named as short as possible, using the all lowercase method, you can use underscores.
3 packages are named as short as possible, using all lowercase methods, and the underscore cannot be used.
The class 4 is named using the Capwords method, and the classes used within the module use _capwords.
5 exception naming uses the Capwords+error suffix method.
6 Global variables are as effective as possible within the module, similar to static in C. There are two methods of implementation, one is the __all__ mechanism, and the other is the prefix an underscore.
7 The function is named using the all lowercase method, you can use underscores.
8 A constant is named using all uppercase, you can use underscores.
The 9 classes of properties (methods and variables) are named using the all lowercase method, which can be underlined.
The 9 class has 3 scopes for public, Non-public, and subclass APIs that can be interpreted as the public, private, protected,non-public attributes in C + +, preceded by an underscore.
11 Class of attributes if the name of the keyword conflict, the suffix underlined, try not to use the abbreviation and other ways.
12 to avoid naming conflicts with sub-class attributes, prefix two is underlined before some properties of the class. For example: Class Foo declared __a, access, only through foo._foo__a, to avoid ambiguity. If the subclass is also called Foo, there is nothing you can do about it.
Methods of class 13 The first argument must be self, and the first parameter of the static method must be CLS.

Seven coding recommendations
The 1 encoding takes into account the efficiency of other Python implementations, such as the high efficiency of the operator ' + ' in CPython (Python), which is very low in Jython, so the. Join () method should be used.
2 Replace ' = = ' as far as possible with ' is ', for example, if X is not None to be superior to if X.
3 using class-based exceptions, each module or package has its own exception class, which inherits from exception.
Do not use bare except,except followed by specific exceptions in the 4 exception.
The code for the try in the 5 exception is as small as possible. Like what:
Try
Value = Collection[key]
Except Keyerror:
return Key_not_found (Key)
Else
return Handle_value (value)
To better than
Try
# Too broad!
Return Handle_value (Collection[key])
Except Keyerror:
# would also catch Keyerror raised by Handle_value ()
return Key_not_found (Key)
6 use StartsWith () and EndsWith () instead of slices for sequence prefix or suffix checking. Like what:
Yes:if foo.startswith (' Bar '): Better Than
No:if Foo[:3] = = ' Bar ':
7 use Isinstance () to compare the type of the object. Like what
Yes:if isinstance (obj, int): Better Than
No:if type (obj) is type (1):
8 Judging the sequence is empty or not empty, there are the following rules
Yes:if not seq:
If seq:
Better than
No:if Len (seq)
If not Len (seq)
9 string do not end with a space.
102 binary data determine how to use if boolvalue.

PEP8 Python Coding specification collation (Python)

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.