Home  >  Article  >  Backend Development  >  Python programming specifications

Python programming specifications

高洛峰
高洛峰Original
2016-11-22 16:35:431042browse

Appropriate blank lines are helpful to increase the readability of the code. You can refer to the following guidelines for adding blank lines:

1) Add blank lines between the definitions of classes and functions;

2) Between import modules of different types Add blank lines;

3) Add blank lines between logical paragraphs in the function, that is, write related codes compactly together as a logical paragraph, with blank lines separating paragraphs;

> Line breaks

Although now Widescreen monitors can already display more than 256 columns of characters on a single screen, but this specification still adheres to the standard that the maximum line length should not exceed 80 characters. There are several ways to fold long lines:

1) Change the long variable name to a short name, such as:

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

It should be changed to:

variable_name1 = this.is.a.very.long.variable_name
variable_name2 = this.is.another.variable_name
variable_name1 = variable_name2s

2) Python will wrap parentheses, square brackets and curly brackets The rows are implicitly concatenated, you can take advantage of this feature. If necessary, you can add an extra pair of parentheses around the expression

3) Add a line continuation character to a long line to force a line break. The position of the line break should be before the operator, and there should be an extra indent after the line break to facilitate maintenance When people look at the code, they can tell that there is a line break when they see the beginning of the line of code, such as:

if color == WHITE or color == BLACK \
    or color == BLUE: # 注意 or 操作符在新行的行首而不是旧行的行尾
do_something(color);

> String

1) Avoid using + and += operators in loops to accumulate strings. Since strings are immutable, doing so creates unnecessary temporary objects and results in quadratic rather than linear runtime. As an alternative, you can add each substring to a list and then use .join to join the lists 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 multi-line strings. Note, however, that it is often cleaner to use implicit line concatenation because multiline strings are inconsistent with the indentation of other parts of the program.

> Naming

Consistent naming can reduce a lot of trouble for developers, and appropriate naming can greatly improve the readability of the code and reduce maintenance costs.

>> Constants

Constant names are all capital letters, with underscores connecting each word, such as

WHITE = 0XFFFFFF
THIS_IS_A_CONSTANT = 1

>> Variables

Variable names are all lowercase, with underscores connecting each word, such as

color = WHITE
this_is_a_variable = 1

Private class members Use a single underscore prefix to identify more public members and less private members.

Variable names should not carry type information because Python is a dynamically typed language. Such as iValue, names_list, dict_obj, etc. are all bad names.

>> Function

The naming rules of function names are the same as variable names.

>> Classes

Use words starting with capital letters (such as CapWords, Pascal style) for class names, and do not use underscores to connect words. For example:

class ThisIsAClass(object):pass

>> Module

Module names are all lowercase. For modules used in packages, you can add an underscore prefix, such as

module.py_
internal_module.py

>> Package

The naming convention of packages is the same as that of modules.

>> Abbreviations

should try to use fully spelled words when naming. There are two types of abbreviations:

1) Commonly used abbreviations, such as XML, ID, etc., should only capitalize the first letter when naming. Such as

class XmlParser(object):pass

2) If the name contains long words, abbreviate a certain word. At this time, it should be used as an agreed abbreviation method, such as removing vowels, the first character containing consonants, etc. For example:

Function is abbreviated as FN

Text abbreviated as TXT

Object

Number is abbreviated as num, etc.

>> The specific naming method

mainly refers to the system reserved word naming method in the form of __xxx__. This kind of naming can also be used in projects. Its significance is that variables in this form are read-only, and class member functions in this form should not be 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):
        # …略

where __id__, __parent__ and __message__ all use system reserved word nomenclature.

>> Import format

1) The order of import, first import Python built-in modules, then import third-party modules, and finally import other modules in self-developed projects; these modules are separated by blank lines .

2) Each import should be on its own line.

3) Do not use from module import * unless it is an import constant definition module or other module where you ensure that there will be no namespace conflicts.

> Assignment

For assignment languages, the main thing is not to do unnecessary alignment, such as

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

没有必要做这种对齐,原因有两点:一是这种对齐会打乱编程时的注意力,大脑要同时处理两件事(编程和对齐);二是以后阅读和维护都很困难,因为人眼的横向视野很窄,把三个字段看成一行很困难,而且维护时要增加一个更长的变量名也会破坏对齐。直接这样写为佳:

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

>  语句

通常每个语句应该独占一行。不过, 如果测试结果与测试语句在一行放得下, 你也可以将它们放在同一行。如果是if语句, 只有在没有else时才能这样做。特别地,绝不要对 try/except 这样做,因为try和except不能放在同一行。


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn