Original link: http://legacy.python.org/dev/peps/pep-0008/
Item |
Detail |
Pep |
8 |
Title |
Style Guide for Python Code |
Version |
c451868df657 |
Last-modified |
2016-06-08 10:43:53-0400 (Wed, June 2016) |
Author |
Guido van Rossum <guido at Python.org> Barry Warsaw <barry at Python.org> Nick Coghlan <ncoghlan at Gmail .com> |
Status |
Active |
Type |
Process |
Content-type |
Text/x-rst |
Created |
05-jul-2001 |
Post-history |
05-jul-2001, 01-aug-2013 |
Introduction Introduction A Foolish consistency is the hobgoblin of Little minds the letter is not as good as no book code lay-out codes layout indentation indent Tabs or Spaces tab or space Maximum the maximum length of line length lines Should a line break before or after a binary operator should I wrap before the two-dollar operator Blank Lines Empty row Source file Encoding sources encoding Imports import module level Dunder names module-class name string quotes strings quote whitespace in Expressions d statements expressions and spaces in a statement Pet Peeves can't stand things other recommendations suggestions Comments comment blocks Comments block comments Inline Comments Line comments Documentation Strings document strings naming conventions naming conventions overriding principle the most important principles descriptive naming describe naming styles Styles Ive naming conventions Convention naming conventions Names to avoid names to be avoided Package and module Names package name and modular name class Names class name Exception Names exception name G Lobal Variable Names global variable name function Names function function and method arguments functions and methods parameters method Names and Instance Variables methods Name and instance variable Constants constant designing for inheritance inherited design public and internal interfaces common and internal interfaces programming programming Suggested Function annotationsFunctional annotation Reference
Introduction Introduction
The Python code coding specification provided in this article is based on the standard library of the major release versions of Python. C code specification for Python's C language see the appropriate PEP guide 1.
This document, along with Pep 257 (specification of document Strings), is adapted from Guido's original Python style Guide, while adding some of Barry's style guide 2.
This normative guide evolves over time, and as the language itself changes, the conventions of the past are eliminated.
Many projects have their own coding specifications, in the event of a specification conflict, the project's own norms first. A Foolish Consistency is the hobgoblin of Little minds do not have A book
One important insight of Guido is that code reading is more frequent than writing. The guidelines provided here are primarily designed to improve the readability of your code, keeping it consistent in a large number of Python code. As Pep 20 mentions, "readability counts".
This is a style guide on consistency. The stylistic consistency of this style guide is very important. More importantly, the style of the project is consistent. Consistency in the style of a module or function is most important.
However, it should be known when it should be inconsistent, and sometimes the code's recommendations do not apply. When there is ambiguity, use your own judgment. Look at the other examples and decide which one is the best, and don't be shy about asking questions.
In particular, do not compromise compatibility in order to comply with PEP conventions.
A few good reasons to ignore certain rules: the readability of the code after the guide is followed, and even the people who follow THE PEP specification find the readability poor. Consistent with the surrounding code (and possibly for historical reasons), although this is an opportunity to clean up other people's clutter (the Real Xtreme Programming style). The problematic code appears before the coding specification is found, and there is no good reason to modify them. When the code needs to be compatible with an older version of Python that does not support coding specifications. Code lay-out Layout Indentation Indent
Each level of indentation uses 4 spaces.
The continuation line should be aligned with its wrapping element, either vertically aligned with parentheses, square brackets and implicit row joins within curly braces, or snap to 3 using a hanging line indent. When using a hanging line indent, you should consider that the first row should not have parameters, and use indents to differentiate yourself as a continuation line.
Recommended:
# align with left parenthesis
foo = long_function_name (Var_one, Var_two,
var_three, Var_four)
# Use more indentation to differentiate def from other rows
long_ Function_name (
var_one, Var_two, Var_three,
var_four):
print (Var_one)
# hanging Line indent should be another line of
foo = Long_ Function_name (
var_one, Var_two,
Var_three, Var_four)
Not recommended:
# When vertical alignment is not used, it is prohibited to place arguments on the first line of
foo = Long_function_name (Var_one, Var_two,
var_three, Var_four)
# When indents are not differentiated from other rows, To increase Indent
def long_function_name (
var_one, Var_two, Var_three,
var_four):
print (Var_one)
The four-space rule is optional for continuation of the line.
Optional:
# Hanging line indents not necessarily 4 spaces
foo = long_function_name (
var_one, Var_two,
Var_three, Var_four)
When the conditional part of an If statement is long enough to be wrapped, note that you can add a space to the two-character keyword connection (for example, if), and then add an opening parenthesis to create a multiline condition with a 4-space indent. This creates a visual conflict with code that uses the same 4-space indentation within the IF statement. PEP does not explicitly indicate how to differentiate between the conditional code and the inline code of the I-send. The options you can use include, but are not limited to, the following:
# no extra indentation
if (this_is_one_thing
and that_is_another_thing):
do_something ()
# adds a comment, There can be some distinction between this_is_one_thing and that_is_another_thing in an editor
that provides syntax highlighting
:
# Since both conditions are True, we can frobnicate.
Do_something ()
# adds an extra indent if (this_is_one_thing and that_is_another_thing) to the statement that the condition is judged
:
do_ Something ()
(Refer to the following discussion about whether to truncate before or after the binary operator)
The curly braces/brackets/parentheses in a multiline structure can be used as the first character on the last line, one line at a single row, like this:
My_list = [
1, 2, 3,
4, 5, 6,
] result
= some_function_that_takes_arguments (
' A ', ' B ', ' C '
, ' d '), ' E ', ' f ',
)
Or you can snap to the first line of a multiline structure, like this:
My_list = [
1, 2, 3,
4, 5, 6,
] result
= some_function_that_takes_arguments (
' A ', ' B ', ' C '
, ' d ', ' e ', ' f ',
)
Tabs or spaces. A tab or a space.
A space is the preferred indentation method.
Tabs can only be used in line with code that uses tab indents as well.
Python3 is not allowed to use both spaces and tab indents.
Python2 codes that mix tabs and space indents should be uniformly converted to spaces.
When you execute Python2 with the-t option on the command line, it emits a warning about the illegal blending of tabs and spaces. When you use –TT, these warnings become errors. It is strongly recommended that you use such parameters. maximum length of Maximum line length
The maximum number of characters for all row limits is 79.
Large chunks of text (document characters or annotations) that do not have a structured limit, and the maximum number of characters per line is limited to 72.
Restricting the width of the editor window allows multiple files to be opened in parallel and works well when you use the Code-checking tool (which displays these two versions in adjacent columns).
The default encapsulation in most tools destroys the visual structure of the code, making the code more difficult to understand. Avoid using the 80 window width of the default configuration in the editor, even if the tool puts a marker in the last column to help you break the row. Some web-based tools may not provide dynamic folding lines at all.
Some teams prefer a longer line width. If the code is maintained primarily by a team, the problem can be achieved by increasing the line length from 80 to 100 characters (it is more efficient to increase the row maximum length to 99 characters), provided that the annotation and document string are still 72 characters in line.
The Python standard library is conservative in that it needs to limit the line width to 79 characters (the document/comment limit is 72).
Longer lines of code select Python's implicit continuation in parentheses, brackets, and curly braces. Fold the long string into multiple lines by wrapping the expression inside the parentheses. This should be done preferentially rather than using a backslash.
The backslash is sometimes still useful. For example, a long, multiple with state statement cannot use an implicit continuation, so the backslash is acceptable:
With open ('/path/to/some/file/you/want/to/read ') as file_1, \
open ('/path/to/some/file/being/written ', ' W ') as File_2:
file_2.write (File_1.read ())
(See the previous discussion of multiline if-statements for further thoughts on this multiline with-statement indentation.) )
Another similar scenario is to use an Assert statement.
Make sure that the appropriate indentation is on the continuation line. Should a line break before or after a binary operator? Should I wrap before the two-dollar operator?
For decades, the recommended style was interrupted after the two-dollar operator. But this affects readability for two reasons: operators are generally distributed in different columns on the screen, and each operator is moved to the previous line of the operand. The following example requires extra notice that the variables are added and the variables are subtracted:
# Not recommended: operator is too far from the operand
income = (gross_wages +
taxable_interest +
(dividends-qualified_dividends)-
Ira_ Deduction-
Student_loan_interest)
To solve this problem of readability, mathematicians and their publishers followed the opposite convention. Donald Knuth explained the traditional rule in his computers and typesetting series: "Although the formulas in the paragraph are always interrupted after the two-dollar operator and the relationship, the displayed formula always interrupts" 4 before the two-dollar operator.
Follow the tradition of mathematics to produce more readable code:
# Recommended: Operators and operands are easy to match
income = (gross_wages
+ taxable_interest
+ (dividends-qualified_dividends)
-IRA _deduction
-Student_loan_interest)
In Python code, it is allowed to break before or after the two-dollar operator, as long as the local conventions are consistent. For new code, it is recommended that you use the Knuth style. Blank Lines Blank line
The definition of the top-level function and class is separated by two blank lines.
The method definition in the class is separated by a blank line.
The related feature groups can be separated by extra empty lines (used sparingly). Blank lines between a bunch of related single-line code can be omitted (for example, a set of virtual implementations dummy implementations).
Use blank lines in functions to differentiate logical segments (use sparingly).
Python accepts control-l (ie ^l) page breaks as spaces, and many tools use them as page delimiters, so you can separate the related paragraphs in a file. Note that some editors and web-based code readers may not recognize control-l as a page break, and another glyph will appear in its place. source file Encoding sources encoding
Code in the Python core release is always encoded in UTF-8 format (or ASCII-encoded in Python2).
Files encoded using ASCII (in Python2) or UTF-8 (in Python3) should not have an encoding declaration.
In a standard library, a non-default encoding should be used only for testing, or when a comment or document string needs to refer to an author name that contains an ASCII character encoding, otherwise, use \x,\u,\u or \ nthe escape to include non-ASCII characters.
For Python 3 and later, the standard library prescribes the following policies (see PEP 3131): All identifiers in the Python standard library must use an ASCII identifier and, where feasible, English words (in many cases, abbreviations and technical terms are non-English). In addition, string literals and annotations must also be ASCII. The only exception is (a) test cases for testing non-ASCII features, and (b) the name of the author. The author's name, if not spelled in Latin alphabet, must provide a transliteration of the Latin alphabet.
Similar policies are encouraged for open source projects with a global audience. Imports Import imports are usually in separate lines, such as:
Recommendation: Import OS
import sys
is not recommended: import sys, OS
But you can do this:
From subprocess import Popen, PIPE
The import is always at the top of the file, after the module annotation and the document string, before the module's global variables and constants.
The import should be grouped in the following order: standard library import related third party library import local application/KUT Import
You should add a blank line between each group of imports.
Absolute path import is recommended, and if the import system does not have the correct configuration (for example, after a directory in the package is in Sys.path), using an absolute path is more readable and performs better (at least providing better error messages):
Import mypkg.sibling from
mypkg import sibling from
mypkg.sibling Import Example
However, the specified relative import path shown is an acceptable alternative to using an absolute path, especially when handling complex package layouts that use absolute paths to import unnecessary verbosity:
From. Import sibling from
. Sibling Import Example
The standard library avoids using complex packages to introduce structures, and always uses absolute paths.
You should not use an implicit relative path to import and delete it in Python 3. When you import a class from a module that contains a class, you often write this:
From MyClass import MyClass from
foo.bar.yourclass import YourClass
If the above wording leads to a clash of names, then write:
Import MyClass
Import Foo.bar.yourclass
Then use the MyClass. MyClass "and" Foo.bar.yourclass.YourClass ". Avoid the import of wildcards (from import *) because doing so does not know what names exist in the namespace, confusing the read interface with many automation tools. For the import of wildcard characters, there is a defensive approach to republishing the internal interface as part of the public API (for example, to overwrite the interface of a pure Python implementation with the definition of an optional accelerator module, and to rewrite definitions that are not known beforehand).
When republishing names in this manner, the following guidelines for public and internal interfaces still apply. module level Dunder names class "Stay" name
Module-level "__author__" such as __all__, __version__, and so on (that is, the name has two prefix underscores and two suffix underscores) should be placed behind the document string and in addition to the from __future__ is preceded by an import expression other than the. Python requires that future import in a module be preceded by a code other than the document string.
Like what:
"" is the example module.
This module does stuff.
"" " From __future__ import barry_as_flufl
__all__ = [' A ', ' B ', ' C ']
__version__ = ' 0.1 ' __author__
= ' Cardinal ' Gles '
import OS
import sys
String Quotes Strings Quote
In Python, single and double quote strings are the same. Pep won't give advice for this. Choose a rule and stick with it. When a string contains either single or double quote characters, use a different outermost symbol to avoid the use of backslashes, which improves readability.
For a three-quote string, always use double quote characters consistent with the document string conventions in Pep 257. whitespace in Expressions and statements expressions and spaces in statements Pet Peeves can't stand the thing
Avoid using extraneous spaces in the following situations: Immediately after parentheses, brackets, or curly braces.
Yes:spam (Ham[1], {eggs:2})
No: spam (ham[1], {eggs:2})
Cling to a comma, semicolon, or colon.
Yes:if x = = 4:print x, y; X, y = y, x
No: if x = = 4:print x, y; x, y = y, X