Python Development Coding Specification

Source: Internet
Author: User
The coding conventions given in this document apply to Python code that makes up the standard library in the main Python release, please refer to the relevant description of the C code style guide in Python's C implementation.
This document was adapted from Guido's original Python style guide and added some of the content from the "Barry's style guides" article. Where there is a conflict, the guide's style rules should be in accordance with the intent of this pep: when there is a conflict, the Guido style shall prevail. This pep is still not finished (in fact, it may never be done).
Consistency in this style guide is important. Consistency within a project is more important. Consistency within a module or function is the most important. But the most important thing is to know when it will be inconsistent-sometimes just without a style guide. When doubts arise, use your best judgment, look at other examples, and decide how to look better. and to Fools!
Two good reasons to break an established rule:
(1) When applying this rule will cause the code to become less readable, even for someone who is accustomed to reading the code according to this rule.
(2) Breaking the rules in order to be consistent with the surrounding code (perhaps for historical reasons), although this is also a good opportunity to clear other clutter (real XP style).

Layout of the Code
Indent in
Default value for Python-mode using emacs: 4 spaces one indent level. For really old code, you do not want to create confusion, you can continue to use a tab with 8 spaces (8-space tabs). Emacs Python-mode automatically discovers the primary indentation level in the file, setting the indent parameter accordingly.

A tab or a space
Never mix tabs and spaces. The most popular way to indent Python is to use only spaces, followed by tabs only, and code that is indented with tabs and spaces is converted to use only spaces. (In Emacs, select the entire buffer and press Esc-x to remove the tabs.) Using the-t option when invoking the Python command-line interpreter, you can warn against mixed tabs and spaces that are not legal in your code, and warnings become errors when you use-TT. These options are highly recommended.
For new projects, it is highly recommended to use only spaces instead of tabs. Many editors have features that make it easy to implement (in Emacs, confirm that Indent-tabs-mode is nil).

Maximum length of a row
There are still many devices around that are limited to 80 characters per line: Moreover, the window is limited to 80 characters. Makes it possible to place multiple windows side-by-side. Using the default folding method on these devices looks a little ugly. Therefore, limit all rows to a maximum of 79 characters (Emacs is accurate to limit the line to 80 characters long), and it is recommended to limit the length to 72 characters for large chunks of text (document strings or notes) that are emitted sequentially.
The preferred way to collapse a long line is to use Pyhon supported parentheses, square brackets, and line continuation in curly braces. If you want, you can add an extra pair of parentheses around the expression, but sometimes the backslash looks better, confirming that the continuation line is properly indented.
Emacs's Python-mode is right to do this. Some examples:
#! Python
Class Rectangle (Blob):
def __init__ (self,width,height,color= ' black ', emphasis=none,highlight=0):
If width = = 0 and Height = = 0 and \
color = = ' red ' and emphasis = = ' strong ' or \
Highlight > 100:
Raise ValueError, "Sorry, you Lose"
If width = = 0 and Height = = 0 and (color = = ' Red ' or
Emphasis is None):
Raise ValueError, "I don ' t think so"
blob.__init__ (Self,width,height,color,emphasis,highlight)

Blank Line
The definition of the top-level function and class is separated by two lines of empty lines, and the definition of the method within the class is separated by a single blank line, and the extra blank line can be used for a group of (conservative) split-related functions, in which a blank line can be omitted in the middle of a set of related sentences. (Example: a set of dumb elements).
When the empty row is used to split the definition of a method, there is also a blank line between the ' class ' line and the first method definition. Use caution when using empty rows in a function to represent a logical paragraph. Python accepts Contol-l (that is, ^l) as a space: Emacs (and some print tools), depending on the character as a page separator, so in your file, you can use them to page the relevant fragments.

Coding
The code in the Python core publication must always use ASCII or Latin-1 encoding (aka Iso-8859-1), and the ASCII file does not have to be encoded cookie,latin-1 is used only if the comment or document string involves an author name that requires Latin-1:
In addition, using the \x escape character is the preferred method of including non-ASCII (NON-ASCII) data in a string.
A partial file of the test suite that implements the code as a pep 263 is an exception.

Import
You should typically import (imports) in a separate row, for example:
No:import sys, OS
Yes:import SYS
Import OS
But it's also possible:
From types import StringType, ListType
Imports are usually placed at the top of the file, only after the module comments and document strings, before the module's global variables and constants. Imports should be placed in groups in sequence:
1. Import of standard libraries (imports)
2. Import of the related main package (i.e., all e-mail packets are major in subsequent import)
3. Application-specific import (imports)
You should place a blank line between each set of imports, and a relative import is not recommended for an internal package import, and the absolute path of the package is used for all imports.
When you import a class from a module that contains classes, you can usually write this:
From MyClass import MyClass
From Foo.bar.YourClass import YourClass
If this causes a local name conflict, then write
Import MyClass
Import Foo.bar.YourClass
Even with "Myclass.myclass" and "Foo.bar.YourClass.YourClass"

Spaces in expressions and statements
Guido do not like to appear in the following places space:
Close to parentheses, square brackets and braces, such as: "Spam (ham[1],{eggs:2})". Always write it as "spam (Ham[1],{eggs:2})".
To cling to a comma, semicolon, or colon, as in:
"If x = = 4:print X,y:x,y = y,x". To always write it
"If x = = 4:print X,y:x,y = y,x".
Close to the argument list of the function call the opening bracket (open parenthesis), such as "spam (1)". Always write it "spam (1)".
Close to an index or slice, beginning with the opening parenthesis, as in:
"Dict [' key '] = list [index]". Always write it "dict[' key '" = List[index] ".
One or more spaces around the assignment (or other) operator that are used in parallel to each other, such as:
#! Python
x= 1
Y= 2
Long_variable = 3
To always write it
#! Python
x = 1
y = 2
Long_variable = 3
(Do not make this style more than 20 years from any of the above, arguing with--guido.) )

Other suggestions
Always place a space on either side of these two-tuple operators: Assignment (=), Comparison (==,<,>,!=,<>,<=, >=,in,not In,is,is not), Boolean operation (And,or,not).
Insert a space around the arithmetic operator, as you would think. Always maintain the same space on both sides of the two-dollar operator.
Some examples:
#! Python
i = i+1
Submitted = submitted + 1
x = x*2-1
Hypot2 = x*x + y*y
c = (a+b) * (A-B)
c = (A + b) * (a)
Do not use spaces around the ' = ' sign used to specify a keyword parameter or a default parameter value, for example:
#! Python
def complex (real, imag=0. 0):
Return Magic (R=real, I=imag)
Do not write more than one statement on the same line:
no:if foo = = ' blah ': do_blah_thing ()
yes:if foo = = ' blah ':
Do_blah_thing ()

No:do_one (): Do_two (): Do_three ()
Yes:do_one ()
Do_two ()
Do_three ()

Comments
Comments that are inconsistent with the code are worse than no comments. Always update comments first when the code is modified! The comment should be a complete sentence, and if the comment is a phrase or sentence, the initial letter should be capitalized unless he is an identifier that begins with a lowercase letter (never change the case of the identifier).
If the comment is short, it is best to omit the end of the period. A comment block usually consists of one or more paragraphs consisting of a complete sentence, each sentence ending with a period. You should use two spaces at the end of the sentence to make the line break and fill work in unison.
When writing in English, word breaks and blanks are available. Python programmers in non-English-speaking Countries: please write your comments in English unless you are 120% confident that the code will not be read by someone who does not understand your language.

Comment Block
Comment Blocks are typically used to follow some (or all) of the code and have the same indentation level as the code. Each line in the comment block starts with ' # ' and a space (unless he is indented text within the comment). The paragraphs within the comment block are split with rows that contain only a single ' # '. The top and bottom side of the comment block is best surrounded by a blank line (or a row below the two lines above, and a comment on a new function definition segment).

In-line comments
An in-line comment is a comment on the same line as the statement, and the in-line comment should be applied sparingly, and the in-line comment should be separated by at least two spaces and statements, which should start with ' # ' and a single space.
x = x+1 # Increment x
If the semantics are clear, then the in-line annotations are unnecessary and in fact should be removed. Don't write like this:
x = x+1 # Increment x
x = x+1 # Compensate for border
But sometimes, this is beneficial:
x = x+1 # Compensate for border

Document string
You should always follow the conventions of writing good document strings PEP 257 [3]. Write a document string for all public modules, functions, classes, and methods. Document strings are not necessary for non-public methods, but you should have a comment that describes what this method does. This comment should be after the "Def" line.
PEP 257 describes the conventions for good document strings. It is important to note that the "" "at the end of a multiline document string should be taken separately, for example:
"" "Return a Foobang
Optional Plotz says to frobnicate the Bizbaz first.
"""
For a single-line document string, the end of "" "is also available on the same line.
Version notes
If you want to include RCS or CVS Miscellaneous (CRUD) in your source file, do this as follows.
#! Python
__version__ = "$Revision: 1. 4 $ "
# $Source: E:/cvsroot/python_doc/pep8. Txt,v $
This line should be included in the module's document string, before all code is split up and down with a blank line.

Naming conventions
The naming conventions of the Python library are a bit confusing, so we will never be able to make them exactly the same, but there are still well-known naming specifications. New modules and packages (including third-party frameworks) must conform to these standards, but for existing inventory in different styles, maintaining internal consistency is preferred.

Description: Naming style
There are many different naming styles. The following helps to identify the naming style being used, independent of their role. The following naming styles are well-known:
B (Single lowercase letter)
B (single capital Letter)
lowercase (lowercase)
Lower_case_with_underscores (lowercase with underline)
Uppercase (UPPERCASE)
Upper_case_with_underscores (with underlined capitalization)
Capitalizedwords (or capwords,camelcase) is named because words can be separated from the case of letters. This is sometimes used as a studlycaps.
Mixedcase (unlike Capitalizedwords, it is the first letter lowercase!)
Capitalized_words_with_underscores (with an underlined first letter capitalized) (ugly!)
Also useful is the short special prefix that aggregates the associated names together in style. This is not commonly used in Python, but for completeness, for example, the Os.stat () function returns a tuple whose elements are traditionally called St_mode, St_size,st_mtime, and so on.
All public functions of the X11 library begin with X. (in Python, this style is generally considered unnecessary because the property and method names are prefixed with the object, and the function name is prefixed with the module masterpiece.) )
In addition, the following special forms with underscores as leading or ending are recognized (these can usually be combined with any custom):
_single_leading_underscore (single underscore as leading): weak "Internal use (internal using)" flag. (for example, "from M import *" Does not import objects that begin with an underscore).
Single_trailing_underscore_ (single underscore end): used to avoid conflicts with Python keywords, for example: "Tkinter.toplevel (master,class_= ' ClassName ')".
_double_leading_underscore (Double underline): The class private name from Python 1.4.
_double_leading_and_trailing_underscore_: The "Magic" object or attribute that exists in the user-controlled (user-controlled) namespace, for example: _init_, _import_, or _file_. Sometimes they are defined by the user to trigger a magical behavior (for example: operator overloading): Sometimes the constructor is inserted for its own use or for debugging purposes. Therefore, in future versions, constructors (loosely defined as Python interpreter and standard library) may intend to create their own list of magical attributes, and user code should generally limit the use of such conventions as their own. User code that wants to be part of the constructor can use a short prefix in the glide line, for example:
_bobo_magic_attr__.

Description: Naming conventions
Names that should be avoided. Never use the character ' l ' (lowercase El (that is, the same as)), ' O ' (capital letter Oh), or ' I ' (capital Letter eye) as the variable name of the single character. In some fonts, these characters cannot be distinguished from numbers 1 and 0. Try to replace with ' l ' when using ' l '.

Module name
The module should be a non-underlined, short, lowercase name. Because the module name is mapped to the file name, some file systems are case insensitive and truncated, and the module name is chosen to be fairly short is important, which is not a problem on UNIX, but it can be a problem when the code is uploaded to Mac or Windows.
When an extension that is written in C or C + + has a companion Python module that provides high-level (for example, a further object-oriented) interface, the C + + module has an underscore leading (such as: _socket). The Python package should be a non-underlined, short, all-lowercase name.

Class name
It is hardly surprising that the class name uses the Capwords convention. The internally used class plus a leading underscore.

Exception name
If a module defines a single exception for all cases, it is often called "error" or "error". It seems that the built-in (extended) module uses "error" (for example: os.error), whereas the Python module usually uses "error" (for example: Xdrlib. Error). The trend seems to be the tendency to use the Capwords exception name.

Global variable Name
(Let's pray that these variables are only meaningful within a module)
These conventions are the same as in functions. The module is designed to be used by the "from M import *" and must be prefixed with an underscore for global variables (and internal functions and classes) to prevent it from being exported (exporting).

Name of function
The function name should be lowercase, and underlined words may be used to increase readability. Mixedcase is only allowed for contexts where this style has prevailed (e.g., threading.py) in order to maintain backward compatibility.

Method name and instance variable
This paragraph is roughly the same as the function: usually lowercase words are used and, if necessary, underlined to increase readability. Python does not enforce the requirement that a leading underscore be used only for internal methods and instances that do not intend to be the public interface of the class: It depends on the programmer's adherence to this Convention.
Using two leading underscores to represent the class's private name, Python joins the names with the class names:
If class Foo has a property named _a, it cannot be accessed with foo._a. (Stubborn users can still get access through foo._foo__a.) )
Typically a double-leading underscore is only used to avoid name collisions with attribute names in classes with subclasses.

The design of the inheritance
Always determine whether the methods and instance variables in a class are to be exposed. In general, you should never expose data variables unless you implement them essentially as records, and people almost always prefer to give them a function as a class interface (some developers of Python 2.2 do it beautifully).
Also, determine if your property should be private. The difference between private and non-private is that the template will never be valid for the original class (The exported Class), while the latter can. You should use inheritance in your brain to design your class, the private attribute must have two leading underscores, no trailing underlines, non-public attributes must have a leading underscore, no trailing underline, public properties without leading and trailing underscores, unless they conflict with reserved words, in which case A single post-underline is better than a pre-or chaotic spelling, for example: Class_ is better than Klass.
The last point is somewhat controversial: if you prefer Klass to class_ than you do, then this is just a matter of consistency.

Design recommendations
A comparison of a single element (singletons), such as none, should always be done with: ' Is ' or ' is not '. When you mean "if X is not None", be careful to write "if X". For example, if you test whether a variable or parameter with the default of none is set to a different value, this value may be false! in the Boolean context (Boolean)
Class-based exceptions are always better than string-based exceptions. Modules and packages should define their own domain-specific base exception classes, which should be subclasses of the built-in exception class. Also always contains a document string for a class. For example:
#! Python
Class Messageerror (Exception):
"" "Base class for errors in the e-mail package. """
Use the String method (methods) instead of a string module unless you must be backwards compatible with Python versions earlier than 2.0. The string method is always very fast, and the same API (application interface) is common to Unicode strings to avoid slicing strings when checking prefixes or suffixes. Replace them with StartsWith () and EndsWith () because they are clear and have fewer errors. For example:
No:if Foo[:3] = = ' Bar ':
Yes:if foo. StartsWith (' Bar '):
The exception is if your code must work in Python 1.5.2 (but we hope it won't happen!). ), the object type comparison should always replace the direct comparison type with isinstance (), for example:
No:if type (obj) is type (1):
Yes:if isinstance (obj, int):
When checking whether an object is a string, remember that it may also be a Unicode string! In Python 2.3,str and Unicode There is a common base class, basestring, so you can do this:
If Isinstance (obj, basestring):
The Python 2.2 type module defines the Stringtypes type for this purpose, for example:
#! Python
From types Import stringtypes
If Isinstance (obj, stringtypes):
In Python 2.0 and 2.1, you should do this:
#! Python
From types import StringType, Unicodetype
If Isinstance (obj, stringtype) or \
Isinstance (obj, unicodetype):
For sequences, (strings, lists, tuples), the fact that using an empty list is false, so that "if not seq" or "if seq" is better than "if Len" or "If not len (seq)". Do not rely on meaningful trailing spaces when writing string literals. This trailing space is visually indistinguishable, and some editors (especially recently, reindent.py) will trim them off. Do not use = = to compare Boolean values to determine if it is true or False (Boolean is new in Pythn 2.3)
No:if greeting = = True:
Yes:if Greeting:

No:if greeting = = True:
Yes:if Greeting:
  • Related Article

    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.