Python Development Code Specification _python

Source: Internet
Author: User
Tags comments function definition inheritance lowercase naming convention string methods in python
The coding conventions given in this document apply to the Python code that makes up the standard library in the main Python release, and consult the relevant description of the C code style guide in Python's C implementation.
This document has been adapted from Guido's original Python style guide and has been added to Barry's style guide. Where there is conflict, guide's style rules should be consistent with the intent of this pep (meaning that when there is a conflict, the Guido style should prevail). THE 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 most important. But the most important thing is to know when it will be inconsistent--sometimes it just doesn't implement style guidance. When there is doubt, use your best judgment, see other examples, and decide how to look better. And be so inquisitive!
Two good reasons to break an established rule:
(1) When applying this rule will cause the code to be readable, even for someone, he is accustomed to reading the code by this rule.
(2) Breaking the rules (and perhaps historical reasons) to keep up with the surrounding code, although this is also a good opportunity to clear other clutter (real XP style).

Layout of code
Indent
Default value for Python-mode using emacs: 4 spaces, one indent level. For really old code, you don't want to create confusion, you can continue using 8-Space tabs (8-space tabs). Emacs Python-mode automatically discovers the main indentation levels in the file, setting the indentation parameters accordingly.

tab or Space
Never mix tabs and spaces. The most popular Python indentation is to use only spaces, followed by only tabs, and code that mixes tabs and spaces indents will be converted to use only spaces. (In Emacs, select the entire buffer and press Esc-x to remove the tabs.) When invoking the Python command-line interpreter, use the-t option to warn against the illegal blending of tabs and spaces in your code, and the warning will become an error when you use-TT. These options are highly recommended.
For new items, it is strongly recommended that you use only spaces instead of tabs. Many editors have features that make them easy to implement (in Emacs, confirm that Indent-tabs-mode is nil).

Maximum length of line
There are still many devices around that are limited to 80 characters per line: Also, the window is limited to 80 characters. Makes it possible to place more than one window side-by. Using the default folding method on these devices looks a bit ugly. Therefore, limit all rows to a maximum of 79 characters (Emacs is accurate enough to limit the line to 80 characters long), and it is recommended that you limit the length to 72 characters for sequentially emitted chunks of text (document strings or notes).
The preferred method for collapsing long rows is to use Pyhon-supported parentheses, brackets, and line continuations within curly braces. If you want, you can add a pair of extra parentheses around the expression, but sometimes using a backslash looks better and confirms that the continuation line is indented properly.
The Python-mode of Emacs is the right thing to do. 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 do"
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 rows, the definition of the inner method is separated by a single blank line, and the extra blank line can be used (conservative) to divide the group of related functions, and the blank lines can be omitted in the middle of a set of related clauses. (for example, a group of dumb elements).
When an empty row is used for the definition of a split method, there is also a blank line between the ' class ' line and the first method definition. Use a blank line in a function, carefully to represent a logical paragraph. Python accepts contol-l (ie ^l) page breaks as spaces: Emacs (and some print tools), depending on the character as a page break, so in your file, you can use them to page the relevant fragment.

Coding
The code in the Python core publication must always use ASCII or Latin-1 encoding (also known as iso-8859-1), and files that use ASCII do not have to be encoded cookie,latin-1 are used only when the annotation or document string involves the author's name requiring 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 Pep 263 is an exception.

Import
You should typically import (imports) in a separate line, for example:
No:import sys, OS
Yes:import SYS
Import OS
But this is also possible:
From types import StringType, ListType
Imports are usually placed at the top of the file, only after module annotations and document strings, before the module's global variables and constants. The imports should be placed sequentially in groups:
1, the standard library import (imports)
2, the related main package (major package) of the import (that is, all the email packets in the subsequent import)
3, specific application import (imports)
You should place a blank line between each group of imports, and the import of the inner package is not recommended to use relative imports, the absolute path of the package is used for all imports.
When you import a class from a module that contains a class, you can usually write this:
From MyClass import MyClass
From Foo.bar.YourClass import YourClass
If this writing 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 don't like spaces in the following places:
Adjacent 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 before a comma, semicolon, or colon, as:
"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 (open parenthesis), such as "spam (1)". Always write it "spam (1)".
To cling to before an open parenthesis, as in an index or slice, as:
"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 with the other, such as:
#! Python
x= 1
Y= 2
Long_variable = 3
To always write it
#! Python
x = 1
y = 2
Long_variable = 3
(don't argue with him over any of the above--guido have developed this style for more than 20 years.) )

Other suggestions
Always place a space on either side of these two-dollar operators: Assignment (=), Comparison (==,<,>,!=,<>,<=, >=,in,not In,is,is not), Boolean operations (And,or,not).
In your opinion, insert a space around the arithmetic operator. Always keep the spaces on both sides of the two-dollar operator consistent.
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-b)
Do not use spaces around the ' = ' number used to specify keyword parameters or default parameter values, 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 code are worse than no annotations. Always prioritize comments when code is modified! Note should be a complete sentence, if the note is a phrase or a sentence, the first letter should be capitalized unless he is an identifier that begins with a lowercase letter (never modify the case of an identifier).
If the comment is short, it is best to omit the end period. A comment block is usually composed of one or more paragraphs consisting of a complete sentence, and each sentence should end with a period. You should use two spaces after the end of the sentence to reconcile the line breaks and padding for Emacs.
When writing in English, word breaks and spaces are available. Python programmers in non-English-speaking countries: Write your notes in English unless you are 120% sure that the code will not be read by someone who doesn't understand your language.

Comment Block
Comment Blocks are usually 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 annotation). The paragraphs within the comment block are split with rows that contain only a single ' # '. Comment block the upper and lower sides are best surrounded by a blank line (or a line below two lines, a comment for a new function definition segment).

In-line comments
An inline comment is a comment on the same line as the statement, and inline comments should be applied cautiously, and the inline annotations should be separated by at least two spaces and statements, which should start with ' # ' and a single space.
x = x+1 # Increment x
If semantics are clear, inline 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 useful:
x = x+1 # compensate for border

Document string
The agreed pep 257 [3] should always be followed by a well-written document string. 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 in a separate row, for example:
"" "Return a Foobang
Optional Plotz says to frobnicate the Bizbaz A.
"""
For a single line of document strings, the end of "" is also available on the same line.
Version Note
If you want to include the RCS or CVS Miscellaneous (CRUD) in your source files, do the following.
#! 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 separated by an empty line.

Naming conventions
The naming convention for the Python library is a bit confusing, so we'll never make it all the same, but there's still a well-established naming code. 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 help identify the naming styles that are 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 (with underlined lowercase)
Uppercase (capital)
Upper_case_with_underscores (uppercase with underlined)
Capitalizedwords (or capwords,camelcase) is named because the word can be written out from the letter's size. This is sometimes used as a studlycaps.
Mixedcase (unlike Capitalizedwords is the first letter lowercase!)
Capitalized_words_with_underscores (with underlined first letter caps) (ugly!)
Also useful is the style of short special prefixes that will be associated with the names aggregated together. This is not commonly used in Python, but for completeness to mention, for example, the Os.stat () function returns a tuple whose elements are traditionally known as St_mode, St_size,st_mtime, and so on.
All public functions of the X11 library begin with X. (in Python, this style is often considered unnecessary because property and method names are prefixed with objects, and function names are prefixed by the module name.) )
In addition, the following special forms that are preceded or terminated by an underscore are recognized (these can usually be combined with any custom):
_single_leading_underscore (single underline for leading): Weak internal use (internal uses) 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, such as: "Tkinter.toplevel (master,class_= ' ClassName ')".
_double_leading_underscore (Double underline): Class private name from Python 1.4.
_double_leading_and_trailing_underscore_: "Magic" object or attribute that exists in the user-controlled (user-controlled) namespace, such as: _init_, _import_, or _file_. Sometimes they are defined by the user to trigger a magical behavior (for example, operator overloading): sometimes inserted by constructors for their own use or for debugging purposes. Therefore, in a future release, the constructor (loosely defined as the Python interpreter and the standard library) may be intended to create its own list of magical attributes, which the user code should normally limit to use as its own. User code intended to be part of the constructor can be combined with short prefixes in the slide line, for example:
_bobo_magic_attr__.

Description: Naming convention
Should be avoided by name. Never use the character ' l ' (lowercase El (that is, the pronunciation, the same below)), ' O ' (capital letter Oh), or ' I ' (capital Letter eye) as the variable name for a single character. These characters cannot be distinguished from numbers 1 and 0 in some fonts. Try to replace it with ' l ' when using ' l '.

Module name
The module should be an underscore-free, short, lowercase name. Because the module name is mapped to the filename, some file system is not case-sensitive and the name is truncated, the module name is selected to be quite short is important, this is not a problem on UNIX, but when the code to the Mac or Windows can be a problem.
When an extension module written in C or C + + has an accompanying Python module providing high-level (for example, a further object-oriented) interface, the C + + module has an underscore leading (e.g., _socket). The Python package should be an underscore-free, short, all lowercase name.

Class name
Hardly expected, the class name uses the Capwords convention. The class used internally plus a leading underline.

Exception name
If a module defines a single exception for all cases, it is often called "error" or "error". It seems that built-in (extended) modules use "error" (for example: Os.error), while Python modules typically use "error" (for example: Xdrlib. Error). The trend seems to be the tendency to use capwords exception names.

Global variable Name
(Let's pray that these variables are meaningful only within one module)
These conventions are the same as those in functions. Modules are designed to be used through "from M import *" and must be prefixed with a prefix of global variables (and internal functions and classes) to prevent them from being exported (exporting).

The name of the function
The function name should be lowercase and may be underlined to increase readability. Mixedcase is only allowed for contexts in which this style already prevails (such as: threading.py) in order to remain backward compatible.

Method name and instance variable
This is generally the same as the function: lowercase words are usually used and, if necessary, separated by an underscore to increase readability. Python does not enforce a leading underline only for internal methods and instances that are not intended to be a common interface for a class: It depends on whether the programmer complies with this Convention.
Using two leading underscores to represent class-private names, Python joins these names and class names together:
If class Foo has an attribute named _a, it cannot be accessed as foo._a. (Stubborn users can still get access through foo._foo__a.) )
Typically, a double leading underline is used only to avoid name collisions with property names in classes that contain subclasses.

Design of inheritance
Always determine whether the method and instance variables in a class are to be exposed. Typically, you never expose a data variable unless you realize that it's essentially a record, and people almost always prefer to give a function as a class interface (some of the developers in Python 2.2 are pretty good at this point).
Also, determine if your attributes 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), which can. You should design your class in your brain with inheritance, private properties must have two leading underscores, no trailing underlines, non-public attributes must have a leading underline, no underline, public properties without leading and trailing underscores unless they conflict with reserved words, in which case A single back underline is better than the preceding or confusing spelling, for example: Class_ is better than Klass.
The last point is controversial: if you prefer Klass to Class_, 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 '. Be careful when you write "if X" when you intend to be "if" not None. For example, when you test whether a variable or parameter with the default of none is set to another value, this value may be false! in the Boolean context (Boolean)
Class-based exceptions are always better than strings based exceptions. Modules and packages should define a specific base exception class within their own domain, and the base class 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 email package. """
Use a String method (methods) instead of a string module unless you must be backward compatible with the previous version of Python 2.0. String methods are always very fast, and the same API (application interface) that is common to Unicode strings avoids slicing strings when checking for 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 comparison of object types 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, it is also possible to remember it as a Unicode string! In Python 2.3,str and Unicode There are common base classes, 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), using an empty list is false this fact, so "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 the value of a Boolean to determine whether it is true or False (the 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.