Concise Python Programming Specification

Source: Internet
Author: User
Tags constant definition logical operators naming convention python script

Rai Yonghao (http://laiyonghao.com)

Note: A concise Python programming specification was previously published (see: http://blog.csdn.net/lanphaday/article/details/2834883), which I made for the company where I was, and when I posted it to my blog, Alignment and other issues have some errors, including some typos. Later, I have made a correction. About 8 years in 2010, I was transferred from C + + development to Python development, and then polished and perfected on the basis of that, forming the second edition. Some time ago simple-is-better.com website forwarded I wrote the previous version of the specification (see: http://simple-is-better.com/news/534), cause everyone's discussion, I one by one explanation not to come, so today take some time to put V2 Edit to publish, ask for communication, correct me.

The following is the full text of the specification:

Python Programming Specification v2 execution
    • This specification uses Pylint and the corresponding configuration file to carry on the detection, regarding the Pylint installation and the configuration see: http://blog.csdn.net/lanphaday/article/details/6089902
Coding
    • All Python script files should be identified on the header of the file as follows or in its compatible format: [Python] View plain copy
      1. #-*-Coding:utf-8-*-
    • The settings editor, which is saved by default in utf-8 format.
Comments
    • The industry generally agrees that Python's annotations are divided into two concepts, a "real" comment that begins with #, and a docstrings. The former shows why the current implementation is chosen and the rationale and difficulty of the implementation, which shows how to use the package, modules, classes, Functions (methods), and even the use of examples and unit tests.
    • Adhere to the principle of proper annotation. The code that does not have technical difficulties persists without comment, and the code that has technical difficulties must be commented. However, unlike annotations, it is recommended to write docstrings for each package, module, class, function (method), unless the code is at a glance, very simple.
Format indent
    • Python relies on indentation to determine the hierarchy of code blocks, beginning with two main whitespace characters: tab and space, but it is strictly forbidden to mix the two.
    • Inside the company, tabs are indented using 2 spaces.
Space
  • Whitespace is meaningful in Python code because Python's syntax relies on indentation, and spaces at the beginning of the line are called leading spaces. In this section, there is no discussion of leading whitespace-related content, only non-leading spaces are discussed. Non-leading spaces do not make sense in Python code, but adding non-leading spaces appropriately can improve the readability of your code.
  • Add spaces before and after two-dollar arithmetic, logical operators, such as: [Python] View plain copy
    1. A = B + C
  • ":" With no spaces at the end of the line, such as branches, loops, functions, and class definition languages; Use a space at the end of a row, such as the definition of a Dict object: [python] View plain copy
    1. D = {' key ': ' value '}
  • Brackets (including parentheses, brackets, and braces) are not preceded by spaces, such as: [HTML] View plain copy
    1. Do_something (Arg1, arg2)
    Instead of [Python] view plain copy
    1. Do_something (Arg1, arg2)
  • Comma followed by a space, preceded by no space;
Blank Line
    • An appropriate blank line is useful for increasing the readability of your code, and there are several guidelines for adding a blank line:
  • Add a blank line between the definitions of classes and functions;
  • Add empty lines between different types of modules in import;
  • Add empty lines between logical paragraphs in the function, that is, to write the relevant code together as a logical paragraph, separated by a blank line between paragraphs;
Break
    • Although the widescreen display is now capable of displaying more than 256 columns of characters on a single screen, this specification still insists that the maximum length of the line must not exceed 78 characters. There are several ways to collapse a long line:
  • Change a short name for the long variable name, such as:
[Python] View plain copy
  1. This._is.a.very.long.variable_name = This._is.another.long.variable_name
should read: [Python] View plain copy
  1. Variable_name1 = This._is.a.very.long.variable_name
  2. Variable_name2 = This._is.another.variable_name
  3. Variable_name1 = Variable_name2s

  • Wrap lines in parentheses, including parentheses, brackets, and braces, such as:

[Python] View plain copy
  1. Class Edit (Widget):
  2. def __init__ (self, parent, width,
  3. Font = font, color = BLACK, pos = pos, style = 0): # Note: Multi-layer indent
  4. Pass
or:
[Python] View plain copy
  1. Very_very_very_long_variable_name = Edit (parent,
  2. Width
  3. Font
  4. Color
  5. POS) # Note: More than one level of indentation
  6. Do_sth_with (Very_very_very_long_variable_name)
  • If the president does not fit the parameters in the first parenthesis, each element is a separate line:
[Python] View plain copy
  1. Very_very_very_long_variable_name = Ui.widgets.Edit (
  2. Panrent,
  3. Width
  4. Font
  5. Color
  6. POS) # Note: More than one level of indentation
  7. Do_sth_with (Very_very_very_long_variable_name)
  • In a long line to add a continuation line break, the position of the line should be in front of the operator, and after wrapping a more indentation, so that the maintenance staff to see the code at the beginning of the code to determine that there is a line break, such as:

[HTML] View plain copy
  1. if color = = White or color = = BLACK \
  2. or color = = BLUE: # Note If the OR operator is at the beginning of a new line instead of the end of the old line, the continuation of the previous line cannot be omitted
  3. do_something (color);
  4. Else
  5. Do_something (Default_color);
Named
    • Consistent naming can reduce a lot of hassle for developers, and proper naming can significantly improve code readability and reduce maintenance costs.
Constant
    • The constant name is all uppercase letters, and the words are connected by underscores, such as:
[Python] View plain copy
  1. White = 0xFFFFFFFF
  2. This_is_a_constant = 1
Variable
    • Variable names are all lowercase, and the words are concatenated by underscores, such as:
[python] view plain copy
  1. color = White
  2. this_is_a_variable = 1
    • Neither the class member variable nor the global variable uses the M or G prefixes. Private class members are identified by using a single underscore prefix, multiple definitions expose members, and less defined private members.
    • Variable names should not have type information, because Python is a dynamic type language. such as Ivalue, Names_list, dict_obj, etc. are not a good name.
Function
    • The function name has the same naming convention as the variable name.
Class
    • Class list words are capitalized, do not use underscores to connect words, and do not add prefixes such as C or T. Such as:

[Python] View plain copy

  1. Class Thisisaclass (object):
  2. Passs

Module
    • Module name all lowercase, for modules used within the package, you can add an underscore prefix, such as:

[Python] View plain copy

  1. module.py
  2. _internal_module.py

Package
    • The package's naming convention is the same as the module.
Abbreviation
    • The name should use all spelling words as far as possible, the abbreviation is as follows two kinds of things:
  • Commonly used abbreviations, such as XML, ID, and so on, should be named with only the first letter, such as:
[python] view plain copy
  1. Class Xmlparser (object):pass
  • The name contains long words, and a word is abbreviated. You should use the abbreviated method of the contract idiomatic, such as removing the vowel, including the first character of the consonant, for example:
  • function abbreviation is FN
  • Text abbreviation for TXT
  • The object abbreviation is obj
  • Count abbreviation for CNT
  • Number is abbreviated to NUM, and so on.
Specific naming methods
    • Mainly refers to the __xxx__ form of the system reserved word naming method. This type of naming can also be used in projects, meaning that variables of this form are read-only and this form of class member functions is not overloaded as much as possible. Such as:
[Python] view plain  copy  
  1. class base (object):   
  2.   def __init__ (self, id, parent  = none):   
  3.      SELF.__ID__ = ID  
  4.     < Span class= "Special" >SELF.__PARENT__&NBSP;=&NBSP;PARENT&NBSP;&NBSP;
  5.   < span class= "keyword" >def __message__ (self, msgid):   
  6.     #&NBSP; slightly   
among them, __id__, __parent__ and __message__ all adopt the system reserved word naming method.
Statement Import
    • The import statement has several principles to follow:
  • Import order, import the Python built-in module first, then import the third-party module, and finally import the other modules in the project that you developed; These modules are separated by blank lines.
  • An import statement imports a module.
  • When you import multiple objects from a module and more than one row, use the following line break method (this syntax is py2.5 for the above version):
[python] view plain copy
  1. From module import (Obj1, Obj2, Obj3, Obj4,
  2. Obj5, Obj6)
  • Do not use the From module import * Unless it is an import constant definition module or other module where you ensure that there are no namespace conflicts.

Assign value
    • For an assignment statement, the main thing is not to do unnecessary alignment, such as:
[Python] view plain  copy  
  1. a         = 1                   #  this is a line comment    
  2. variable = 2                   #  another line comment   
  3. fn       = callback_ Function  #  or line comment   
There is
no need to do this alignment for two points: one is that this alignment disrupts programming attention, that the brain handles two things at the same time (programming and alignment), and that it is difficult to read and maintain in the future because the horizontal vision of the human eye is very narrow, and it is difficult to see three fields as one row. And adding a longer variable name to the maintenance will also break the alignment. It is best to write this directly:
[python] view plain copy
  1. A = 1 # This is a line comment
  2. variable = 2 # Another line comment
  3. fn = callback_function # or line comment
Branching and cycling
    • For branching and looping, there are a few points to note:
  • Do not write a line such as:
[Python] View plain copy
  1. If not FLG: pass
and the
[python] view plain copy
  1. For I in xrange (ten): print i
are not good code, should be written
[python] view plain copy
  1. If not FLG:
  2. Pass
  3. For I in xrange (Ten):
  4. Print I

Note: the example in this document that is written in one line is due to the reason of typesetting, and should not be used as a basis for continuous coding.

  • The conditional expression should be written pythonic enough, such as the following form of conditional expression is poor:
[Python] View plain copy
  1. If Len (alist)! = 0:do_something ()
  2. If alist! = []: do_something ()
  3. if s! = "": do_something ()
  4. If var! = none:do_something ()
  5. If var! = false:do_something ()
the above statement should be written as:
[Python] View plain copy
  1. If Seq:do_somethin () # Note that the name here has also changed
  2. If Var:do_something ()
  • Use the ELSE clause of the loop statement to simplify the code when you need it.
Already have code
    • For the code that is already in the project, it is possible that the legacy causes of history do not conform to this specification and should be considered a tolerable exception, allowing existence, but should not perpetuate the old style in the new code.
    • For third-party modules, which may not conform to this specification, should also be considered as a tolerable exception, allowing existence, but should not be used in new code with the style of a third-party module.
    • tab-and-space indentation is ' not tolerated ', and you should use the-t or-TT option to troubleshoot this possibility when you run the project. In the case of mixed use, if it is the base Class library code developed by the company, the class library maintenance personnel should be notified of the modification; third-party modules can be used to push developers to fix problems by submitting patches.
Already have a style
    • Developers often have their own coding style before they join the project, and should write the code after joining the project. In particular, the Hungarian nomenclature, because of the type information, is not suitable for Python programming and should not be applied in a Python project.

Concise Python Programming Specification

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.