[Python] Code Specification [Original]

 

refer to

https://blog.csdn.net/ratsniper/article/details/78954852

https://www.cnblogs.com/wangcp-2014/p/4608265.html

https://www.jianshu.com/p/c7455c178059

 

indentation

  • Uniformly use 4 spaces for indentation
  • Continuation lines should be aligned to their enclosing element, either vertically using parentheses, brackets, and implicit line joins within curly braces, or using hanging line indents. When using hanging line indentation, you should consider that the first line should not have parameters, and use indentation to distinguish yourself as a continuation line.

 

recommend:

# 与左括号对齐
foo = long_function_name(var_one, var_two,
                         var_three, var_four)

# 用更多的缩进来与其他行区分
def long_function_name(
        var_one, var_two, var_three,
        var_four):
    print(var_one)

# 挂行缩进应该再换一行
foo = long_function_name(
    var_one, var_two,
    var_three, var_four)

 

Not recommended

# 没有使用垂直对齐时,禁止把参数放在第一行
foo = long_function_name(var_one, var_two,
    var_three, var_four)

# 当缩进没有与其他行区分时,要增加缩进
def long_function_name(
    var_one, var_two, var_three,
    var_four):
    print(var_one)

 

line length

  • The maximum character limit for all lines is 79 (can be slightly more than 80 in special cases, but must not exceed 120)
  • Large blocks of text (document characters or comments) with no structural limit, limited to a maximum of 72 characters per line.

 

quotation marks

Simply put, natural language uses double quotes, and machine tags use single quotes, so most of the code should use single quotes

  • Use double quotes "..." for natural language, such as error messages; in many cases, unicode, use u"Hello World"
  • Use single quotes '...' for machine identifiers, such as keys in dict
  • Regular expressions use native double quotes, r"..."
  • docstrings use triple double quotes """..."""

 

Blank line

  • The definitions of top-level functions and classes are separated by two blank lines.
  • Method definitions within a class are separated by a blank line.

 

for example:

class A:

    def __init__(self):
        pass

    def hello(self):
        pass


    def main():
        pass

 

coding

  • The file uses UTF-8 encoding
  • Add #--conding:utf-8-- to the header of the file (not required for Python 3 and above)

 

ImportImport

  • Imports are usually on separate lines
  • Imports are always at the top of the file, after module comments and docstrings, and before module globals and constants
  • Import order grouping (the order is: standard library import, related third-party library import, local library import, there is a blank line between each group of imports)
  • It is recommended to use absolute path to import

 

for example:

# 推荐
import os

import sys

# 不推荐
import sys, os

 

Comments

  • Comments that contradict the code are worse than no comments, and when the code changes, update the corresponding comment first!
  • Comments should be complete sentences. If a note is a phrase or sentence, its first word should be capitalized, unless it is an identifier that starts with a lowercase letter (never change the case of an identifier!).
  • If the comment is short, the trailing period can be omitted. Block comments generally consist of one or more paragraphs of complete sentences, and each sentence ends with a period.
  • Two spaces should be used at the end of a sentence.
  • When writing in English, follow the writing style of Strunk and White.
  • Python programmers in non-English speaking countries, please write comments in English unless you are 120% sure that your code will not be read by people in other languages.

 

block comment

  • “#”There is a space after the number, and the paragraphs are separated by a blank line (the "#" sign is also required)

 

for example:

 # 块注释
 # 块注释
 #
 # 块注释
 # 块注释

 

Inline comments

  • Use inline comments sparingly.
  • Inline comments are comments that run alongside code statements. Inline comments and code must be separated by at least two spaces. Comments start with # and a space.
  • In fact, inline comments are unnecessary and distracting if the state is obvious.

 

docstring

  • Document all public modules, functions, classes and methods.
  • Non-public methods are not necessary, but should have a comment describing what the method does. This comment should come after the def line.
  • PEP 257 describes conventions for writing good documentation. It is important to note that the closing triple quotes used in multi-line documentation should be on their own line
  • For single-line documentation, the trailing triple quote should be on the same line as the documentation.

 

for example:

"""Return a foobang

Optional plotz says to frobnicate the bizbaz first.

"""

 

file name

  • All lowercase, can use underscore

 

Package names

  • Should be short, lowercase names. If underscore improves readability can be added

 

class name

  • Class names generally use the capitalized convention, such as MyClass
  • In cases where the interface is documented and primarily used for invocation, the function naming style can be used instead.
  • Note that there is a separate convention for naming built-in variables: most built-in variables are single words (or two words concatenated), and capitalized nomenclature is only used for exception names or internal constants.

 

Function name

  • Function names should be lowercase, separated by underscores if you want to improve readability.
  • Mixed-case is only used in cases where it was originally primarily mixed-case for compatibility (such as threading.py), to maintain backward compatibility.

 

method parameters

  • Always use self as the first parameter of instance methods.
  • Always use cls as the first parameter of a class static method.
  • If a function parameter name conflicts with an existing keyword, adding a single underscore at the end is better than abbreviation or random spelling. So class_ is better than clss. (maybe it's better to use synonyms to avoid this conflict)

 

variable name

  • Variable names are all lowercase, and each word is connected by an underscore
  • Private class members are identified with a single underscore prefix, more public members are defined, and fewer private members are defined

 

constant name

  • All constant names are capitalized, and each word is connected by an underscore

 

programming advice

  • Code should be written in a way that does not harm other Python implementations (PyPy, Jython, IronPython, Cython, Psyco, etc.). 

For example, don't rely on the efficient built-in concatenation statements a += b or a = a + b in CPython. This optimization is fragile even in CPython (it only works for certain types) and doesn't show up in implementations that don't use reference counting. In performance-critical libraries, ".join() can be used instead. This ensures that character associations occur in linear time across implementations.

 

  • When comparing with a singleton object like None, you should always use is or is not, and never use the equals operator.

Also, if you write if x, be careful if you mean if x is not None. For example, when testing whether a variable or parameter whose default value is None is set to another value. This other value should be a value that can be a bool type false in the context.

 

  • Use the is not operator instead of not ... is . While the two expressions are functionally identical, the former is easier to read and takes precedence.

 

 

Guess you like

Origin blog.csdn.net/jiandanokok/article/details/109424568