Python Programming specification

Source: Internet
Author: User

1,python Programming Specification > coding
All Python script files should be on the header of the file #-*-Coding:utf-8-*-is used to set the editor, which is saved by default to Utf-8 format.
> Notes
The industry generally agrees that Python's annotations are divided into two types, a "real" annotation that begins with #, for example, to indicate why the current implementation is selected and the rationale and difficulty of the implementation
The other is docstrings, for example, to show how to use the package, modules, classes, Functions (methods), even including using examples and unit tests to adhere to the appropriate annotation principles.



Docstrings, unless the code is at a glance, very simple.
> Indent
4 spaces.
> Spaces

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.

1) in the two-yuan arithmetic, the logical operator before and after the space: such as a = B + c;2) after the unary prefix operator without spaces, such as if!flg:pass;3) ":" With the end of the line without spaces, such as branches, loops, functions and class definition language; Use a space at the end of the line, such as: Dict Object Definition D = {' key ':  ' value '}4) brackets (with parentheses, brackets, and braces) without spaces, such as: Do_something (arg1, arg2) instead of do_something (Arg1, arg2)
5) do not precede commas, semicolons, and colons with spaces, but should add (except at line end) 6) Do not use spaces to vertically align multiple lines of markup, as this will be a burden for maintenance (for:, #,=, etc.)
> Empty Line

An appropriate blank line is useful for increasing the readability of your code, and there are several guidelines for adding a blank line:

1) Add empty lines between the definitions of classes and functions, 2) Add empty lines between different types of import modules, 3) Add empty lines between logical paragraphs in the function, i.e., write the relevant code together as a logical paragraph, separated by a blank line between the 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 80 characters. There are several ways to collapse a long line:

1) for a long variable name for a short name, such as:

This.is.a.very.long.variable_name = This.is.another.long.variable_name

should read:

variable_name1 = This.is.a.very.long.variable_namevariable_name2 = This.is.another.variable_namevariable_name1 = Variable_name2s

2) Python connects the parentheses, the brackets, and the lines in the braces implicitly, and you can take advantage of this feature. If you want, you can add an extra pair of parentheses around the outside of the expression

3) In a long line to join the continuation of the line break, the position of the line should be in front of the operator, and after wrapping a more indentation, so that the maintenance personnel to see the code at the beginning of the code can be determined that there is a line-breaking , such as:

if color = = White or color = = BLACK     or color = = BLUE: # Note the OR operator at the beginning of a new line rather than at the end of the line of the old line do_something (color);
> String
1. Avoid accumulating strings with the + and + = operators in the loop. Because the string is immutable, doing so creates unnecessary temporary objects and results in a two-time rather than linear run time.
As an alternative, you can add each substring to the list and then use the. Join connection list after the loop ends. (You can also write each substring to a Cstringio.stringio cache
2. Use triple double quotes instead of triple single quotes for multiline strings. Note, however, that implicit row joins are usually clearer, because multiline strings do not conform to the indentation of other parts of the program.
> Naming
Consistent naming can reduce a lot of hassle for developers, and proper naming can significantly improve code readability and reduce maintenance costs.
>> Constants

The constant name is all uppercase letters, and each word is connected by an underscore, such as

White = 0xffffffthis_is_a_constant = 1
>> variables

Variable names are all lowercase, and each word is connected by an underscore, such as

color = whitethis_is_a_variable = 1

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.

>> functions
The function name has the same naming convention as the variable name.
>> class

Words that begin with the class name in uppercase letters (such as capwords, Pascal style) do not use underscores to connect words. Such as:

Class Thisisaclass (object):p
>> Modules

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

module.py_internal_module.py
>> Bags
Package naming convention is the same as module
>> Abbreviations

The name should use all spelling words as far as possible, the abbreviation is as follows two kinds of things:
1) commonly used abbreviations, such as XML, ID, etc., should be named with only the first letter, such as

Class Xmlparser (object):p

2) 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:

The function abbreviation is fntext abbreviation for txtobject abbreviation for objcount abbreviation for cntnumber abbreviation for NUM, etc.
>> 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

Class Base (object):    def __init__ (self, id, parent =none):        self.__id__ = id        self.__parent__ = parent    def __message__ (self, MsgId):        # ... Slightly

Among them, __id__, __parent__ and __message__ all adopt the system reserved word naming method.

>> Import Formats
    1. 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 a blank line.
    2. Each import should have an exclusive line.
    3. 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 the assignment language, the main thing is not to do unnecessary alignment, such as:

A            = 1                               # This is a line comment variable = 2                               # Another line comment 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:

a = 1 # 这是一个行注释variable = 2 # 另一个行注释fn = callback_function # 还是行注释
> Statements

Typically, each statement should have a single row. However, if the test results and test statements are placed on one line, you can also put them on the same line. If this is an if statement, you can do so only if there is no else. In particular, never do this to try/except, because try and except cannot be placed on the same line.

2, references

    • Google Python Programming style guide

3, Document modification history

Python Programming specification

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.