Learn Python Writing specifications PEP8 question notes

Source: Internet
Author: User

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.

Code Sample Message
E1 Indentation
E101 Indentation contains mixed spaces and tabs
E111 Indentation a multiple of four
E112 Expected an indented block
E113 Unexpected indentation
E114 Indentation is not a multiple of four (comment)
E115 Expected an indented block (comment)
E116 Unexpected indentation (comment)
E121 (*^) Continuation line under-indented for hanging indent
E122 (^) Continuation line missing indentation or outdented
E123 (*) Closing bracket does not match indentation of opening bracket ' s line
E124 (^) Closing bracket does not match visual indentation
E125 (^) Continuation line with same indent as Next logical line
E126 (*^) Continuation line over-indented for hanging indent
E127 (^) Continuation line over-indented for visual indent
E128 (^) Continuation line under-indented for visual indent
E129 (^) Visually indented line with same indent as Next logical line
E131 (^) Continuation line unaligned for hanging indent
E133 (*) Closing bracket is missing indentation
E2 Whitespace
E201 Whitespace after ' ('
E202 whitespace before ') '
E203 Whitespace before ': '
E211 Whitespace before ' ('
E221 Multiple spaces before operator
E222 Multiple spaces after operator
E223 TAB before operator
E224 tab after operator
E225 Missing whitespace around operator
E226 (*) Missing whitespace around arithmetic operator
E227 Missing whitespace around bitwise OR shift operator
E228 Missing whitespace around modulo operator
E231 Missing whitespace after ', ', '; ', or ': '
E241 (*) Multiple spaces after ', '
E242 (*) tab after ', '
E251 Unexpected spaces around Keyword/parameter equals
E261 At least spaces before inline comment
E262 Inline comment should start with ' # '
E265 Block comment should start with ' # '
E266 Too many leading ' # ' for block comment
E271 Multiple spaces after keyword
E272 Multiple spaces before keyword
E273 TAB after keyword
E274 TAB before keyword
E275 Missing whitespace after keyword
E3 Blank Line
E301 Expected 1 blank line, found 0
E302 Expected 2 blank lines, found 0
E303 Too many blank lines (3)
E304 Blank lines found after function decorator
E305 Expected 2 blank lines after end of function or class
E4 Import
E401 Multiple imports on one line
E402 module level import not at top of file
E5 Line length
E501 (^) Line too long (> characters)
E502 The backslash is redundant between brackets
E7 Statement
E701 Multiple statements on one line (colon)
E702 Multiple statements on one line (semicolon)
E703 Statement ends with a semicolon
E704 (*) Multiple statements on one line (Def)
E711 (^) Comparison to none should being ' if cond is none: '
E712 (^) Comparison to true should are ' if cond is True: ' or ' if cond: '
E713 Test for membership should is ' not in '
E714 Test for object identity should was not '
E721 (^) Do not compare types, use ' isinstance () '
E731 Do not assign a lambda expression, use a Def
E741 Do not use variables named ' l ', ' O ', or ' I '
E742 Do not define classes named ' L ', ' O ', or ' I '
E743 Do not define functions named ' l ', ' O ', or ' I '
E9 Runtime
E901 SyntaxError or Indentationerror
E902 IOError
W1 Indentation Warning
W191 Indentation contains tabs
W2 Whitespace warning
W291 Trailing whitespace
W292 No newline at end of file
W293 Blank line contains whitespace
W3 Blank Line Warning
W391 Blank line at end of file
W5 Line break Warning
W503 (*) Line break occurred before a binary operator
W6 Deprecation warning
W601 . Has_key () is deprecated, use ' in '
W602 Deprecated form of raising exception
W603 ' <> ' is deprecated, use '! = '
W604 Backticks is deprecated, use ' repr () '

Learn Python Writing specifications PEP8 question notes

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.