For details about common PEP8 encoding specifications in Python, pythonpep8
Common PEP8 encoding specifications for Python
Code Layout
Indent
- Each level of indentation uses four spaces.
- Vertical implicit indent or suspension indent is used in parentheses.
EXAMPLE:
# (Vertical implicit indent) align with left brace foo = long_function_name (var_one, var_two, var_three, var_four) # (hanging indent) usually only one more indentation foo = long_function_name (var_one, var_two, var_three, var_four) # (hanging indent) but in the following case, you need to add more indentation, which is distinguished from the subsequent statement blocks def long_function_name (var_one, var_two, var_three, var_four ): print (var_one) # Roll Back my_list = [1, 2, 3, 4, 5, 6,] result = some_function_that_takes_arguments ('A', 'B', 'C ', 'D', 'E', 'F ',)
Error example:
# When vertical alignment is not used, the first line cannot have parameters. Foo = long_function_name (var_one, var_two, var_three, var_four) # The suspension indent of the parameter cannot be different from that of subsequent code blocks. Def long_function_name (var_one, var_two, var_three, var_four): print (var_one) # do not roll back the right brackets. my_list = [1, 2, 3, 4, 5, 6,] is not recommended. result = some_function_that_takes_arguments ('A', 'B', 'C', 'D', 'E', 'F ',)
Maximum Width
- The maximum width of each line cannot exceed 79 characters
- You can use a backslash to resume a row.
- Do not use a backslash to continue rows in parentheses
EXAMPLE:
# Use the backslash ('/path/to/some/file/you/want/to/read') as file_1 to continue the row without parentheses, \ open ('/path/to/some/file/being/written', 'w') as file_2: file_2.write (file_1.read () # continue row in parentheses, try again after the operator class Rectangle (Blob): def _ init _ (self, width, height, color = 'black', emphasis = None, highlight = 0 ): if (width = 0 and height = 0 and color = 'red' and emphasis = 'strong 'or highlight> 100): raise ValueError ("sorry, you lose ") if width = 0 and height = 0 and (color = 'red' or emphasis is None ): raise ValueError ("I don't think so -- values are % s, % s" % (width, height ))
Empty row
- The two empty rows are used to separate the definition of top-level functions and classes.
- A single empty row is used to split the methods in the class definition.
EXAMPLE:
# The method definition of the class is separated by a single blank line, and the empty lines of the two lines are separated by the top-level functions and class definitions. Class A (object): def method1 (): pass def method2 (): passdef method3 (): pass
Module Import
- Each imported module should be in a separate line
- The import order is as follows: (empty rows are required for each module type import. The order of modules in each group is listed from top to bottom in ascending order according to the first letter of the module)
- Standard Library
- Related third-party Libraries
- Local Database
EXAMPLE:
# Import by the first letter of the module. Follow the recursive import activeimport adidasimport create
Error example:
# Importing multiple modules in one row import sys, OS, and knife # import createimport activeimport beyond without the first letter
String
Single quotation marks and double quotation marks are used in the same way, but must exist in pairs. They cannot be used together. (double quotation marks are recommended for sentences. single quotation marks are used for words, but not mandatory .)
EXAMPLE:
# Single quotes have the same effect as double quotes. name = 'jmilkfan 'name = "Hey Guys! "
Spaces in expressions and statements
Avoid spaces in parentheses
EXAMPLE:
spam(ham[1], {eggs: 2})
Error example:
spam( ham[ 1 ], { eggs: 2 } )
Comma, colon, avoid spaces before semicolon
EXAMPLE:
if x == 4: print x, y; x, y = y, x
Error example:
if x == 4 : print x , y ; x , y = y , x
There must be no space before the left parenthesis of the function call.
EXAMPLE:
spam(1)dct['key'] = lst[index]
Error example:
spam (1)dct ['key'] = lst [index]
You cannot add multiple spaces before and after the assignment operator because of alignment.
EXAMPLE:
x = 1y = 2long_variable = 3
Error example:
x = 1y = 2long_variable = 3
Place a space on both sides of the binary operator
- Compound operators involved in = (+ =,-=, etc)
- Comparison operators (=, <,> ,! =, <>,<=, >=, In, not in, is, is not)
- Logical operators (and, or, not)
EXAMPLE:
A = ba or B # space name = get_name (age, sex = None, city = Beijing) is not required for operators in parentheses)
Note
Comment Block
The comment block is usually used before the code and has the same indentation as the code. Each line starts with '#' and # is followed by a single space.
EXAMPLE:
# Have to define the param `args(List)`, # otherwise will be capture the CLI option when execute `python manage.py server`.# oslo_config: (args if args is not None else sys.argv[1:])CONF(args=[], default_config_files=[CONFIG_FILE])
Single line comment (unnecessary comment should be avoided)
EXAMPLE:
x = x + 1 # Compensate for border
Document string
EXAMPLE:
# Multi-line documents. the first line is capitalized and the ending "" should be a separate line "" Return a foobangOptional plotz says to frobnicate the bizbaz first. "# single-line document, ending with" on the same line. "" Return a foobang """
Naming rules
Package and module name:
The package name and module name should be short, all of which should be in lower case. You can use single-underline to connect multiple letters.
Class Name:
Follow the camper name
class MyClass(object): pass
Global variable name:
The global variable name should be used only within the module as far as possible. For modules that may be imported using the statement from moduleName import variableName, the _ all _ mechanism should be used to prevent global variables from being imported by other modules, or a prefix underline should be added at the beginning of the global variable name.
EXAMPLE:
_name = 'name'
Function Name
The function name should be in lowercase.
EXAMPLE:
vcenter_connection = ''
Constant name
Constants are all represented by the concave camper rule of uppercase letters, which is usually defined in the top lattice of the module.
EXAMPLE:
MAX_OVERFLOW = ''TOTAL = 1
Method Name and instance variable
The non-public method and instance variable start with a prefix underline
Sometimes, in order to avoid conflicts with the subclass name, we may use two underscores (_).
Note that if the attribute of class Foo is named _ a, the attribute cannot be set to Foo. _ a (persistent users can still use Foo. _ Foo _ a). Therefore, the double-Prefix underline is used only to avoid name conflicts with the attributes of the base class.
Programming recommendations
None is or is not, instead of =
Use is not to replace not... Is, the former is more readable
EXAMPLE:
# Yesif foo is not None# Noif not foo is None
Use the function definition keyword def instead of lambda to assign a value to the identifier, which is more suitable for the return and string representation.
# Yesdef f(x): return 2*x# Nof = lambda x: 2*x
Exception classes should inherit from Exception rather than BaseException
In Python 2, raise ValueError ('message') is used instead of raise ValueError and 'message'
(Considering compatibility with python3 and the convenience of continued rows)
When capturing exceptions, specify the specific exceptions as much as possible, and try not to use catch t Exception. What problems should be caught instead of the problem?
EXAMPLE:
# Yes (capture specific exceptions) try: import platform_specific_module__t ImportError: platform_specific_module = None # No (do not capture globally) try: import platform_specific_module__t: platform_specific_module = None
Try/try t clause should contain as few code as possible to avoid blocking other errors.
EXAMPLE:
# Yestry: value = collection [key] unique T KeyError: return key_not_found (key) else: return handle_value (value) # Notry: return handle_value (collection [key]) unique T KeyError: # The KeyError in handle_value () may be captured, instead of the return key_not_found (key) of the collection)
If a function or method does not return a value, it must explicitly return None.
# Yesdef foo(): return None# Nodef foo(): return
Use the string method instead of the string Module
The string method is always faster after python 2.0 and uses the same API as the Unicode string.
Use. startswith () and. endswith () instead of string slices to check prefix and suffix
Startswith () and endswith are more concise and help reduce errors
EXAMPLE:
# Yesif foo.startswith('bar'):# Noif foo[:3] == 'bar':
Use isinstance () instead of object type comparison
EXAMPLE:
# Yesif isinstance(obj, int):# Noif type(obj) is type(1):
The bool of an empty sequence object is False:
# Yesif not seq: passif seq: pass# Noif len(seq): passif not len(seq): pass
Do not use = for bool comparison
# Yesif greeting: pass# Noif greeting == True passif greeting is True: # Worse pass
Thank you for reading this article. I hope it will help you. Thank you for your support for this site!