concise overview

Concise Overview

1. Encoding

  • If there are no special circumstances, the file Always use UTF-8 encoding

  • If there are no special circumstances, the #-*-coding:utf-8-*-mark must be added to the file header

2. Code format

##2.1. Indentation

  • Use 4 spaces for indentation

2.2. Line width

Each line of code should try not to exceed 80 characters (it can slightly exceed 80 in special circumstances, but the maximum length cannot be More than 120)

Reason:

  • This is helpful when viewing side-by-side diff

  • Convenience View the code under the console

  • If it is too long, it may be a design flaw

##2.3, quotation marks

Simply put, natural language uses double quotes, and machine markings use single quotes, so

in the code should mostly use single quotes

    Naturally The language uses double quotes "..."
  • For example, error messages; in many cases it is still unicode, use u"Hello World"

    machine Use single quotes '...' for identification. For example, the key in dict
  • regular expression uses native double quotes r"..."
  • Document string (docstring) Use three double quotes """..."""
2.4, blank line

    Two empty lines between module-level functions and class definitions;
  • One empty line between class member functions;
  • class A:
        def __init__(self):
            pass
        def hello(self):
            pass
    def main():
        pass
    You can use multiple blank lines to separate multiple groups of related functions
  • You can use blank lines to separate logically related codes in functions
2.5. Encoding

    The file uses UTF-8 encoding
  • File header Add #-*-conding:utf-8-*-identifier
3. Import statement

The import statement should be written in separate lines

# 正确的写法
import os
import sys
# 不推荐的写法
import sys,os
# 正确的写法
from subprocess import Popen, PIPE
import语句应该使用 absolute import
# 正确的写法
from foo.bar import Bar
# 不推荐的写法
from ..bar import Bar

    The import statement should be placed at the head of the file, after the module description and docstring, and before global variables;
  • The import statement should be arranged in order , separate each group with a blank line

  • import os
    import sys
    import msgpack
    import zmq
    import foo
    When importing class definitions of other modules, you can use relative import
  • from myclass import MyClass
    If a naming conflict occurs, you can use the namespace
  • import bar
    import foo.bar
    bar.Bar()
    foo.bar.Bar()
4, spaces

    Leave one space on both sides of the binary operator [=,-, =,==,>,in,is not, and]:
  • # 正确的写法
    i = i + 1
    submitted += 1
    x = x * 2 - 1
    hypot2 = x * x + y * y
    c = (a + b) * (a - b)
    # 不推荐的写法
    i=i+1
    submitted +=1
    x = x*2 - 1
    hypot2 = x*x + y*y
    c = (a+b) * (a-b)
    In the parameter list of the function, there must be a space after ,
# 正确的写法
def complex(real, imag):
    pass
# 不推荐的写法
def complex(real,imag):
    pass
  • In the parameter list of the function, do not add spaces on both sides of the default value equal sign

# 正确的写法
def complex(real, imag=0.0):
    pass
# 不推荐的写法
def complex(real, imag = 0.0):
    pass
  • After the brackets, do not add extra spaces before the right bracket

# 正确的写法
spam(ham[1], {eggs: 2})
# 不推荐的写法
spam( ham[1], { eggs : 2 } )
  • Do not add extra spaces before the left bracket of the dictionary object

# 正确的写法
dict['key'] = list[index]
# 不推荐的写法
dict ['key'] = list [index]
  • Do not use extra spaces to align assignment statements

# 正确的写法
x = 1
y = 2
long_variable = 3
# 不推荐的写法
x             = 1
y             = 2
long_variable = 3

5. Line breaks

Python supports parentheses Line breaks within. There are two situations at this time.

1. The second line is indented to the beginning of the bracket

foo = long_function_name(var_one, var_two,
                         var_three, var_four)

2. The second line is indented by 4 spaces, which is suitable for the situation where the starting bracket is a new line

def long_function_name(
        var_one, var_two, var_three,
        var_four):
    print(var_one)

Use backslash\line break, binary operator., etc. should appear at the end of the line; long strings can also be line wrapped using this method

session.query(MyTable).\
        filter_by(id=1).\
        one()
print 'Hello, '\
      '%s %s!' %\
      ('Harry', 'Potter')

Compound statements are prohibited, that is, one line contains multiple statements:

# 正确的写法
do_first()
do_second()
do_third()
# 不推荐的写法
do_first();do_second();do_third();

if/for/while must be line-wrapped:

# 正确的写法
if foo == 'blah':
    do_blah_thing()
# 不推荐的写法
if foo == 'blah': do_blash_thing()

6, docstring

The two most fundamental points in the docstring specification:

1. All public modules, functions, classes, and methods should be written in docstring. Private methods are not necessarily required, but should be provided with a block comment after the def.

2. The end """ of the docstring should occupy a line by itself, unless this docstring has only one line.

"""Return a foobar
Optional plotz says to frobnicate the bizbaz first.
"""
"""Oneline docstring"""
Continuing Learning
||
submitReset Code