Concise Python programming specification V2.

Source: Internet
Author: User
Tags constant definition python script

Lai Yonghao (http://laiyonghao.com)

Note: I previously published a concise Python programming specification (see: http://blog.csdn.net/lanphaday/article/details/2834883), which was developed for my company at that time. When I published my blog, alignment and other problems all have some errors and some typos. Later, I made another correction. Around the 8 years in 2010, I switched from C ++ development to Python development. Then I finished and improved it on that basis to form the second version. Some time ago the simple-is-better.com website forwarded me to write the previous version of the specification (see: http://simple-is-better.com/news/534), caused everyone's discussion, I can not explain one by one, so today, I will take some time to edit V2 and release it. Please contact and correct me.

The full text is as follows:

Python programming specification V2 execution
  • This specification uses pylint and the corresponding configuration file for detection, for pylint installation and configuration see: http://blog.csdn.net/lanphaday/article/details/6089902
Encoding
  • All Python script files should be identified by the following mark or its compatible format on the header:

 

# -*- coding:utf-8 -*-

  • 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.
    Format 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.
    • The company uses two tabs with spaces for indention.
    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.
    • Add spaces before and after binary arithmetic and logical operators, for example:
    • a = b + c
  • ":" 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, such as the definition of a dict object: view plaincopy to clipboardprint?
    1. D = {'key': 'value '}
    d = {'key' : 'value'}
  • Parentheses (including parentheses, square brackets, and curly braces) do not contain spaces, such as: View plaincopy to clipboardprint?
    1. Do_something (arg1, arg2)
    do_something(arg1, arg2)

    Instead of view plaincopy to clipboardprint?

    1. Do_something (arg1, arg2)
    do_something( arg1, arg2 )
  • A space is added after a comma, and no space is added before it;
  • Empty row
    • Appropriate blank lines help increase the readability of the code. You can refer to the following guidelines for adding blank lines:
    • Add blank rows between class and function definitions;
    • Process rows between different types of import modules;
    • Add blank lines to the logical sections in 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:
    • Change the long variable name to a short name, for example:
    View plaincopy to clipboardprint?
    1. This. _ is. A. Very. Long. variable_name = This. _ is. Another. Long. variable_name
    this._is.a.very.long.variable_name = this._is.another.long.variable_name

    Should be changed to: View plaincopy to clipboardprint?

    1. Variable_name1 = This. _ is. A. Very. Long. variable_name variable_name2 = This. _ is. Another. variable_name variable_name1 = variable_name2s
    variable_name1 = this._is.a.very.long.variable_name variable_name2 = this._is.another.variable_name variable_name1 = variable_name2s
    • Wrap a line in parentheses (including parentheses, square brackets, and curly brackets), for example:
    View plaincopy to clipboardprint?
    1. Class edit (widget): def _ init _ (self, parent, width, font = font, color = Black, Pos = POs, style = 0): # Note: multi-layer indent pass
    Class edit (widget): def _ init _ (self, parent, width, font = font, color = Black, Pos = POs, style = 0): # Note: multi-layer indent pass
    Or:

    View plaincopy to clipboardprint?
    1. Very_very_very_long_variable_name = edit (parent, width, Font, color, POS) # Note: Multiple indentation do_sth_with (very_very_very_long_variable_name)
    Very_very_very_long_variable_name = edit (parent, width, Font, color, POS) # Note: Multiple indentation do_sth_with (very_very_very_long_variable_name)
    • If the arguments in the first bracket cannot be placed, each element occupies a single line:
    View plaincopy to clipboardprint?
    1. Very_very_very_long_variable_name = UI. Widgets. Edit (panrent, width, Font, color, POS) # Note: Multiple indentation do_sth_with (very_very_very_long_variable_name)
    Very_very_very_long_variable_name = UI. Widgets. Edit (panrent, width, Font, color, POS) # Note: Multiple indentation do_sth_with (very_very_very_long_variable_name)
    • When a long row is added with a strong line break, the position of the line break should be prior to the operator, and an indentation should be added after the line break, 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:
    View plaincopy to clipboardprint?
    1. 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); else: do_something (default_color );
    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); else: do_something (default_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, for example:
    View plaincopy to clipboardprint?
    1. White = 0 xffffffff this_is_a_constant = 1
    WHITE = 0xffffffff THIS_IS_A_CONSTANT = 1
    Variable
    • All variable names are in lowercase, and each word is connected by an underscore, for example:
    View plaincopy to clipboardprint?
    1. Color = white this_is_a_variable = 1
    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:
    View plaincopy to clipboardprint?
    1. Class thisisaclass (object): passs
    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, for example:
    View plaincopy to clipboardprint?
    1. Module. py _ internal_module.py
    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:
    • Common abbreviations, such as XML and ID, should also be capitalized when naming, such:
    View plaincopy to clipboardprint?
    1. Class xmlparser (object): Pass
    class XmlParser(object):pass
    • 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:
    View plaincopy to clipboardprint?
    1. Class base (object): def _ init _ (self, ID, parent = none): Self. _ id _ = ID self. _ parent _ = parent def _ message _ (self, msgid ):#... Omitted
    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:
    • 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.
    • An import statement is used to import a module.
    • 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 ):
    View plaincopy to clipboardprint?
    1. From module import (obj1, obj2, obj3, obj4, obj5, obj6)
    from module import (obj1, obj2, obj3, obj4, obj5, obj6)
    • 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
    • Do not make unnecessary alignment for the value assignment statement, for example:
    View plaincopy to clipboardprint?
    1. A = 1 # This is a line comment variable = 2 # Another line comment fn = callback_function # Or a line comment
    A = 1 # This is a line comment variable = 2 # Another line comment fn = callback_function # Or a 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:

    View plaincopy to clipboardprint?
    1. A = 1 # This is a line comment variable = 2 # Another line comment fn = callback_function # Or a line comment
    A = 1 # This is a line comment variable = 2 # Another line comment fn = callback_function # Or a line comment
    Branches and loops
    • Note the following points for the branches and loops:
    • Do not write a line, such:
    View plaincopy to clipboardprint?
    1. If not flg: Pass
    if not flg: pass
    And

    View plaincopy to clipboardprint?
    1. For I in xrange (10): print I
    for i in xrange(10): print i
    None of them are good code and should be written

    View plaincopy to clipboardprint?
    1. If not flg: Pass for I in xrange (10): print I
    if not 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.

    • The preparation of conditional expressions should be pythonic enough, for example, the following forms of conditional expressions are poor:
    View plaincopy to clipboardprint?
    1. If Len (alist )! = 0: do_something () If alist! = []: Do_something () If s! = "": Do_something () If var! = None: do_something () If var! = False: do_something ()
    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:

    View plaincopy to clipboardprint?
    1. If seq: do_somethin () # note that the name here also changes if var: do_something ()
    If seq: do_somethin () # note that the name here also changes if var: do_something ()
    • 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.
    • The indentation mixed with tabs and spaces is '''intolerable '''. You should use the-T or-TT option to check this possibility when running the project. 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.

     

    From: http://blog.csdn.net/lanphaday/article/details/6601123

    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.