Python commonly used PEP8 encoding specification details

  • 2020-05-24 05:45:33
  • OfStack

Python commonly used PEP8 encoding specification

Code layout

The indentation

Use 4 Spaces for each indentation level. Use vertical implicit indentation in parentheses or use suspension indentation.

EXAMPLE:


# ( Vertical implicit indentation ) Align left parenthesis 
foo = long_function_name(var_one, var_two,
    var_three, var_four)

# ( Hanging indent ) 1 Just as often 1 Layer of the indentation 
foo = long_function_name(
 var_one, var_two,
 var_three, var_four)

# ( Hanging indent )  But here's what happens ,  Need to add more 1 Layer indentation,   Distinguish it from subsequent blocks of statements 
def long_function_name(
 var_one, var_two, var_three,
 var_four):
 print(var_one)



#  Close bracket back 
my_list = [
 1, 2, 3,
 4, 5, 6,
]
result = some_function_that_takes_arguments(
 'a', 'b', 'c',
 'd', 'e', 'f',
)

Error demonstration:


#  Do not use vertical alignment when a 1 Rows cannot have arguments. 
foo = long_function_name(var_one, var_two,
 var_three, var_four)

#  The suspension indentation of a parameter is indistinguishable from the subsequent block indentation. 
def long_function_name(
 var_one, var_two, var_three,
 var_four):
 print(var_one)

#  Close parenthesis is not retractable and is not recommended 
my_list = [
 1, 2, 3,
 4, 5, 6,
 ]

result = some_function_that_takes_arguments(
 'a', 'b', 'c',
 'd', 'e', 'f',
 )

The biggest line width

The maximum line width per line should not exceed 79 characters You can use a backslash for line continuation There is no need to use a backslash to continue a line in parentheses

EXAMPLE:


#  To continue a line without parentheses,   Use backslashes 
with open('/path/to/some/file/you/want/to/read') as file_1, \
 open('/path/to/some/file/being/written', 'w') as file_2:
 file_2.write(file_1.read())

#  The continuation of the line in parentheses,   Try to extend the line 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))

A blank line

Two empty lines are used to separate the top-level function from the class definition A single blank line is used to split the methods in the class definition

EXAMPLE:


#  The method definition of a class is separated by a single empty line, and the definition of a top-level function and a class is separated by two empty lines. 
class A(object):
 def method1():
 pass

 def method2():
 pass


def method3():
 pass

Module import

Each imported module should be in a separate line The import order is as follows: (the import of each module type shall be separated by empty lines, and the order of the modules in each group shall be arranged in ascending order from top to bottom according to the first letter of the module)

The standard library Related third square library The local library

EXAMPLE:


#  Import by module alphabetical order ,  According to the recursive 
import active
import adidas
import create

Error example:


# 1 Row imports multiple modules 
import sys, os, knife

#  Do not import by initial 
import create
import active
import beyond

string

Single and double quotation marks are the same, but must be in pairs. (double quotation marks are recommended for sentences and single quotation marks are not mandatory for words.)

EXAMPLE:


#  Single and double quote effects 1 sample 
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 } )

Avoid Spaces before commas, colons, and semicolons

EXAMPLE:


if x == 4: print x, y; x, y = y, x

Error example:


#  Do not use vertical alignment when a 1 Rows cannot have arguments. 
foo = long_function_name(var_one, var_two,
 var_three, var_four)

#  The suspension indentation of a parameter is indistinguishable from the subsequent block indentation. 
def long_function_name(
 var_one, var_two, var_three,
 var_four):
 print(var_one)

#  Close parenthesis is not retractable and is not recommended 
my_list = [
 1, 2, 3,
 4, 5, 6,
 ]

result = some_function_that_takes_arguments(
 'a', 'b', 'c',
 'd', 'e', 'f',
 )

0

The function call must not have a space before the left parenthesis

EXAMPLE:


spam(1)
dct['key'] = lst[index]

Error example:


spam (1)
dct ['key'] = lst [index]

Operators such as assignment cannot have multiple Spaces added before and after them because of alignment

EXAMPLE:


#  Do not use vertical alignment when a 1 Rows cannot have arguments. 
foo = long_function_name(var_one, var_two,
 var_three, var_four)

#  The suspension indentation of a parameter is indistinguishable from the subsequent block indentation. 
def long_function_name(
 var_one, var_two, var_three,
 var_four):
 print(var_one)

#  Close parenthesis is not retractable and is not recommended 
my_list = [
 1, 2, 3,
 4, 5, 6,
 ]

result = some_function_that_takes_arguments(
 'a', 'b', 'c',
 'd', 'e', 'f',
 )

3

Error example:


#  Do not use vertical alignment when a 1 Rows cannot have arguments. 
foo = long_function_name(var_one, var_two,
 var_three, var_four)

#  The suspension indentation of a parameter is indistinguishable from the subsequent block indentation. 
def long_function_name(
 var_one, var_two, var_three,
 var_four):
 print(var_one)

#  Close parenthesis is not retractable and is not recommended 
my_list = [
 1, 2, 3,
 4, 5, 6,
 ]

result = some_function_that_takes_arguments(
 'a', 'b', 'c',
 'd', 'e', 'f',
 )

4

Place 1 space on either side of the 2 meta operator

Complex operators involving = (+=, -=, etc.) The comparison operator (==, < , > , != , < > , < = , > = , in , not in , is , is not ) Logical operators (and, or, not)

EXAMPLE:


#  Do not use vertical alignment when a 1 Rows cannot have arguments. 
foo = long_function_name(var_one, var_two,
 var_three, var_four)

#  The suspension indentation of a parameter is indistinguishable from the subsequent block indentation. 
def long_function_name(
 var_one, var_two, var_three,
 var_four):
 print(var_one)

#  Close parenthesis is not retractable and is not recommended 
my_list = [
 1, 2, 3,
 4, 5, 6,
 ]

result = some_function_that_takes_arguments(
 'a', 'b', 'c',
 'd', 'e', 'f',
 )

5

annotation

Comment block

Comment blocks are usually applied in front of the code and have the same indentation as the code. Each line begins with a '#' followed by a single space.

EXAMPLE:


#  Do not use vertical alignment when a 1 Rows cannot have arguments. 
foo = long_function_name(var_one, var_two,
 var_three, var_four)

#  The suspension indentation of a parameter is indistinguishable from the subsequent block indentation. 
def long_function_name(
 var_one, var_two, var_three,
 var_four):
 print(var_one)

#  Close parenthesis is not retractable and is not recommended 
my_list = [
 1, 2, 3,
 4, 5, 6,
 ]

result = some_function_that_takes_arguments(
 'a', 'b', 'c',
 'd', 'e', 'f',
 )

6

Single-line comments (unnecessary comments should be avoided)

EXAMPLE:


x = x + 1 # Compensate for border

docstring

EXAMPLE:


#  Multi-line document ,  The first letter of the first line is capitalized and the last letter is capitalized  """  It should be a separate line 
"""Return a foobang
Optional plotz says to frobnicate the bizbaz first.
"""

#  A one-line document,   At the end of the  """  In the same 1 Line. 
"""Return a foobang"""

Naming rules

Package and module names:

Package and module names should be short, all in lower case, and multiple letters can be joined using a single underscore.

The name of the class:

Follow the hump


#  Do not use vertical alignment when a 1 Rows cannot have arguments. 
foo = long_function_name(var_one, var_two,
 var_three, var_four)

#  The suspension indentation of a parameter is indistinguishable from the subsequent block indentation. 
def long_function_name(
 var_one, var_two, var_three,
 var_four):
 print(var_one)

#  Close parenthesis is not retractable and is not recommended 
my_list = [
 1, 2, 3,
 4, 5, 6,
 ]

result = some_function_that_takes_arguments(
 'a', 'b', 'c',
 'd', 'e', 'f',
 )

9

Global variable name:

The global variable name should be used within the module as far as possible. For imported modules which may be imported with from moduleName import variableName, the mechanism of s 162en__ should be used to prevent the global variable from being imported by other modules, or a leading underscore should be added at the beginning of the global variable name.

EXAMPLE:


_name = 'name'

The function name

The function name should be all lowercase for the concave hump rule.

EXAMPLE:


vcenter_connection = ''

Constant names

Constants are all represented by the concave hump rule of uppercase letters, usually defined in the top cell of a module

EXAMPLE:


MAX_OVERFLOW = ''
TOTAL = 1

Method names and instance variables

Private methods and instance variables begin with a leading underscore

Sometimes you might want to avoid a subclass name conflict by using two leading underscores

Note that if the property of class Foo is named s. S. S. S. S. S. S. S. S. S. S. S. S. S. S. S. S. S. S. S. S. S. S. S.

Programming advice

None comparisons use is or is not instead of ==

is not instead of not... is, the former is more readable

EXAMPLE:


# Yes
if foo is not None

# No
if not foo is None

Use the function definition keyword def instead of lambda to assign the identifier, which is more suitable for callbacks and string representations


# Yes
def f(x): 
 return 2*x

# No
f = lambda x: 2*x

Exception classes should inherit from Exception, not BaseException

Python 2 USES raise ValueError('message') instead of raise ValueError, 'message'

(consider the convenience of python3 compatibility and line renewal)

When catching exceptions, specify the specific exception as much as possible, and try not to use except Exception. What should be caught instead of the problem occurring

EXAMPLE:


# Yes ( Catch specific exceptions )
try:
 import platform_specific_module
except ImportError:
 platform_specific_module = None

# No ( Don't globally capture )
try:
 import platform_specific_module
except:
 platform_specific_module = None

Keep the code in the try/except clause as small as possible so as not to mask other errors

EXAMPLE:


# Yes
try:
 value = collection[key]
except KeyError:
 return key_not_found(key)
else:
 return handle_value(value)

# No
try:
 return handle_value(collection[key])
except KeyError:
 #  You might catch it  handle_value() In the  KeyError,  Rather than  collection  the 
 return key_not_found(key)

A function or method returns None explicitly when it does not return a value


# Yes
def foo():
 return None

# No
def foo():
 return

Use the string method instead of the string module

Since python 2.0 the string method has always been faster and USES the same API as the Unicode string

Use.startswith () and.endswith () instead of string slices to check for prefixes and suffixes

startswith() and endswith are more concise and reduce errors

EXAMPLE:


# Yes
if foo.startswith('bar'):

# No
if foo[:3] == 'bar':

Instead of comparing object types, use isinstance()

EXAMPLE:


# Yes
if isinstance(obj, int):

# No
if type(obj) is type(1):

The bool of the null sequence type object is False:


# Yes
if not seq:
 pass
if seq:
 pass

# No
if len(seq):
 pass
if not len(seq):
 pass

Do not compare bool with ==


# Yes
if greeting:
 pass

# No
if greeting == True
 pass
if greeting is True: # Worse
 pass

Thank you for reading, I hope to help you, thank you for your support of this site!


Related articles: