UPDATE: The new version of the specification was released on April 9, July 12, 2011. For details, refer to: Workshop.
This article was first published on the blog of liyong Hao (Lianhua butterfly): Ghost.
Concise Python programming specifications
Encoding
All Python script files should be marked with #-*-coding: UTF-8-*-on the header -*-. Set the editor, Which is saved as UTF-8 by default.
Note
The industry generally agrees that python annotations are divided into two concepts: one is the "true" annotation starting with # and the other is docstrings. The former shows why the current implementation is selected and the principles and difficulties of this implementation. The latter shows how to use this package, module, class, function (method), and even use examples and unit tests.
Adhere to the principles of appropriate annotations. Do not comment on codes that do not have any technical difficulties. You must comment on codes that do not have any technical difficulties. But unlike comments, it is recommended to write docstrings for each package, module, class, and function (method) unless the code is clear at a glance, it is very simple.
Indent
Python depends on indentation to determine the level of the code block. There are two main types of blank characters at the beginning of the line: tab and space. If you use tab indentation, Set Tab to 4 spaces.
We recommend that you use tabs with four spaces for indentation.
Space
Spaces make sense in Python code. Because Python syntax depends on indentation, spaces at the beginning of a row are called leading spaces. This section does not discuss content related to leading spaces, but only non-leading spaces. Non-leading spaces are meaningless in Python code, but adding them appropriately can improve code readability.
1) Add spaces before and after binary arithmetic and logical operators, for example, A = B + C;
2) There is no space after The unary prefix operator, such as if! Flg: pass;
3) ":" No spaces are added before and after the end of a row, such as the branch, loop, function, and Class Definition Language. spaces are added at both ends of a non-line end, for example, dict object definition d = {'key': 'value '}.
4) parentheses (including parentheses, square brackets, and curly braces) are not enclosed by spaces, such as do_something (arg1, arg2), rather than do_something (arg1, arg2 );
5) Add a space after the comma (,) and no space before it; s
Empty row
Appropriate blank lines help increase the readability of the code. You can refer to the following guidelines for adding blank lines:
1) Add blank lines between class and function definitions;
2) process rows between import modules of different types;
3) add blank lines to the logical section of the function, that is, compress the relevant code together. As a logical section, the sections are separated by blank lines;
Broken Line
Although the current wide-screen display can display more than 256 characters on a single screen, this specification still adheres to the maximum length of the Line cannot exceed 78 characters. The following methods are used to collapse long rows:
1) Change the short name for the long variable name, for example:
This. is. A. Very. Long. variable_name = this. Is. Another. Long. variable_name
Should be changed:
Variable_name1 = this. Is. A. Very. Long. variable_name
Variable_name2 = this. Is. Another. variable_name
Variable_name1 = variable_name2s
2) wrap a line in parentheses (including parentheses, square brackets, and curly brackets), for example:
Class edit (cbase ):
Def _ init _ (self, parent, width,
Font = font, color = Black, Pos = POs, style = 0 ):
Or:
Very_very_very_long_variable_name = edit (parent ,/
Width ,/
Font ,/
Color ,/
Pos)
If the arguments in the first bracket cannot be placed, each element occupies a single line:
Very_very_very_long_variable_name = UI. Widgets. Edit (/
Panrent ,/
Width ,/
Font ,/
Color ,/
Pos)
3) Add a strong line break to a long line. The line break should be at the beginning of the operator and one more indent after line feed, to enable the maintenance personnel to see the beginning of the code line when reading the code, it can be determined that there is a line break here, such:
If color = white or color = Black/
Or color = Blue: # note that the OR operator is at the beginning of a new line rather than the end of the old line.
Do_something (color );
Name
Consistent naming can reduce a lot of trouble for developers, while Proper naming can greatly improve code readability and reduce maintenance costs.
Constant
All the letters of a constant name are uppercase, and each word is connected by an underscore, as shown in figure
White = 0 xffffff
This_is_a_constant = 1
Variable
All variable names are in lowercase, and each word is connected by an underscore, as shown in figure
Color = white
This_is_a_variable = 1
No m or G prefix is used for both class member variables and global variables. Private class members are identified by a single underline prefix. Multiple public members are defined and less private members are defined.
Variable names should not contain type information, because python is a dynamic type language. For example, ivalue, names_list, and dict_obj are all poorly named.
Function
The naming rules for function names are the same as those for variable names.
Class
Class names use uppercase letters, do not use underscores to connect words, and do not add prefixes such as C and T. For example:
Class thisisaclass (object ):
Passs
Module
All module names are in lower case. You can add an underline prefix to the modules used in the package, as shown in figure
Module. py
_ Internal_module.py
Package
The package naming rules are the same as those for modules.
Abbreviations
You should try to use all words for naming. The abbreviations are as follows:
1) Common abbreviations, such as XML and ID, should also be capitalized, such
Class xmlparser (object): Pass
2) The name contains long words, which are abbreviated to a word. In this case, the abbreviated form should be agreed to, such as removing the vowel and containing the first character of the consonants. For example:
Function is abbreviated as fn.
The abbreviation of text is TXT.
Object is abbreviated as obj.
Count stands for CNT
Number is abbreviated as num.
Specific naming method
It mainly refers to the system reserved wordname method in the form of _ XXX. This type of name can also be used in projects. It means that variables in this form are read-only, and class member functions in this form should not be overloaded as much as possible. For example
Class base (object ):
Def _ init _ (self, ID, parent = none ):
Self. _ id _ = ID
Self. _ parent _ = parent
Def _ message _ (self, msgid ):
#... Omitted
Both _ id _, _ parent _, and _ message _ use the system reserved name.
Statement
Import
The import statement follows the following principles:
1) import order: first import the python built-in module, then import the third-party module, and finally import other modules in the self-developed project; these modules are separated by blank lines.
2) An import statement is used to import a module.
3) when multiple objects are imported from the module and more than one row exists, use the following line breaking method (supported by py2.5 or a later version ):
From module import (obj1, obj2, obj3, obj4,
Obj5, obj6)
4) do not use from module import * unless it is an import constant definition module or another module that you ensure will not conflict with the namespace.
Assignment
For the value assignment language, do not make unnecessary alignment, such:
A = 1 # This is a line comment
Variable = 2 # comment on another line
Fn = callback_function # line comment
There is no need for such alignment for two reasons: first, this alignment will disrupt the attention of programming, and the brain needs to handle two things simultaneously (programming and alignment ); second, reading and maintenance will be very difficult in the future, because the horizontal field of vision of the human eye is very narrow, it is very difficult to regard the three fields as one line, adding a longer variable name during maintenance also breaks the alignment. It is better to write it like this:
A = 1 # This is a line comment
Variable = 2 # comment on another line
Fn = callback_function # line comment
Branches and loops
Note the following points for the branches and loops:
1) do not write a line, such:
If! Flg: Pass and for I in xrange (10): print I are not good code and should be written
If! Flg:
Pass
For I in xrange (10 ):
Print I
Note: the example of writing a line in this document is for typographical reasons and cannot be used as a basis for continuous encoding.
2) The preparation of conditional expressions should be pythonic enough, for example, the following forms of conditional expressions are poor:
If Len (alist )! = 0: do_something ()
If alist! = []: Do_something ()
If s! = "": Do_something ()
If var! = None: do_something ()
If var! = False: do_something ()
The preceding statement should be written as follows:
If seq: do_somethin () # note that the name is changed here
If var: do_something ()
3) when necessary, use the else clause of the loop statement to simplify the code.
Existing Code
The existing code in the project may not comply with this specification due to historical reasons. It should be regarded as a tolerable special case and allowed to exist. However, the old style should not be continued in the new Code.
Third-party modules may not comply with this specification, and should also be considered as tolerable special cases that permit the existence of such modules. However, the style of third-party modules should not be used in new code.
Indentation mixed with tabs and spaces is intolerable. When running a project, use the-T or-TT option to check this possibility. In case of mixed use, if it is the basic class library code developed by the company, the Class Library maintenance personnel should be notified to modify the code; third-party modules can be urged to correct the problem by submitting patches and other methods.
Existing Style
Developers often have their own coding style before joining the project. After joining the project, the code should be written based on this specification. Especially the Hungarian naming method, which contains type information, is not suitable for python programming and should not be used in Python projects.