pyhton code specification

>

Python code standards

Foreword

Python learning journey, take a look at the Python code standards, they have a sense of yourself first, and gradually in subsequent learning habit

table of Contents

Python code standards

A concise overview

1, coding

  • As no special circumstances, the file shall be encoded using UTF-8
  • The absence of exceptional circumstances, must be added to the file header #-*-coding:utf-8-*-logo

2, code format

2.1, indent

  • Unified use 4 spaces to indent

2.2, line width

Each line preferably not exceed 80 characters (in special cases may be slightly more than 80, but no longer than 120)

the reason:

  • This is helpful when viewing the diff side-by-side in
  • Easy to look at the code in console
  • Too long it may be design flaws

2.3, quotes

Simply put, natural language use double quotes, marking machines use single quotes, so the code most should use single quotes

  • Natural language use double quotes "..."
    such as error messages; in many cases, or unicode, usingu"你好世界"
  • Machine identification using single quotes '...'
    , for example, in the key dict
  • Regular expressions use double quotes native r"..."
  • Document string (the docstring of) use three double quotes """......"""

2.4, a blank line

  • Between module functions and classes defined in two blank rows;
  • Blank line between the member function;
class A:

    def __init__(self):
        pass

    def hello(self):
        pass


def main():
    pass   
  • A plurality of blank lines may be spaced groups of related functions
  • Function can be used in the blank line separator code logic associated

2.5, coding

  • File using UTF-8 encoding
  • File header adding #-*-conding:utf-8-*-logo

3, import statements

  • The import statement should write Branch
# 正确的写法
import os
import sys

# 不推荐的写法
import sys,os

# 正确的写法
from subprocess import Popen, PIPE
  • import statements should use the Absolute import
# 正确的写法
from foo.bar import Bar

# 不推荐的写法
from ..bar import Bar
  • After the import statements should be placed in the file header, put the module description and docstring, before the global variables;
  • import statement should be arranged in order, separated by a blank line between each
import os
import sys

import msgpack
import zmq

import foo
  • When introduced into the class definition of the other modules, can be introduced using a relatively
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, space

  • In a binary operation on both sides of a space for each 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)
  • The function's parameter list, ,then there must be space
# 正确的写法
def complex(real, imag):
    pass

# 不推荐的写法
def complex(real,imag):
    pass
  • Function's parameter list, the default value is equal on both sides avoiding spaces
# 正确的写法
def complex(real, imag=0.0):
    pass

# 不推荐的写法
def complex(real, imag = 0.0):
    pass
  • After opening parenthesis, do not add extra spaces before the closing parenthesis
# 正确的写法
spam(ham[1], {eggs: 2})

# 不推荐的写法
spam( ham[1], { eggs : 2 } )
  • Before opening parenthesis dictionary objects do extra spaces
# 正确的写法
dict['key'] = list[index]

# 不推荐的写法
dict ['key'] = list [index]
  • Do not align the extra space assignment and use of
# 正确的写法
x = 1
y = 2
long_variable = 3

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

5, line

Python support wrap in parentheses. Then there are two cases.

  1. The second line to the beginning brackets indented
foo = long_function_name(var_one, var_two,
                         var_three, var_four)
  1. The second line indented four spaces for the start on wrapping circumstances brackets
def long_function_name(
        var_one, var_two, var_three,
        var_four):
    print(var_one)

Backslash \newline, binary operators + .other end of the line should appear; long string may wrap this method

session.query(MyTable).\
        filter_by(id=1).\
        one()

print 'Hello, '\
      '%s %s!' %\
      ('Harry', 'Potter')

Prohibition compound statement that contains more than one line statement:

# 正确的写法
do_first()
do_second()
do_third()

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

if/for/whileYou must want to change the line:

# 正确的写法
if foo == 'blah':
    do_blah_thing()

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

6、docstring

docstring present specification which most two points:

  1. All public modules, functions, classes, methods, should write docstring. Private methods do not necessarily need, but it should provide a block comments to explain after def.
  2. End of docstring "" "should be on a separate line, unless this docstring only one line.
"""Return a foobar
Optional plotz says to frobnicate the bizbaz first.
"""

"""Oneline docstring"""

Second, comments

1 comment

1.1, block comments

"#" After a number of empty cells, paragraphs member separated by blank lines (also need to "#" sign)

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

1.2, line comments

Use at least two separate spaces and statements, be careful not to use meaningless comments

# 正确的写法
x = x + 1  # 边框加粗一个像素

# 不推荐的写法(无意义的注释)
x = x + 1 # x加1

1.3, it is recommended

  • In the critical parts of the code (or more complex place), you can write comments to try to write a comment

  • More important comment period, the use of multiple equal sign separated, can be more eye-catching, highlighting the importance of

app = create_app(name, options)


# =====================================
# 请勿在此处添加 get post等app路由行为 !!!
# =====================================


if __name__ == '__main__':
    app.run()

2, document annotation (Docstring)

As docstring generally appear in the document head modules, functions and classes of the head, so that the document can be acquired by __doc__ target object in python.
Editors and IDE automatically prompt can also be provided according docstring.

  • Documentation Comments to "" "beginning and end of the first line does not wrap, if multiple lines, wrap the bottom line is necessary, the following is an example of Google's docstring style
# -*- coding: utf-8 -*-
"""Example docstrings.

This module demonstrates documentation as specified by the `Google Python
Style Guide`_. Docstrings may extend over multiple lines. Sections are created
with a section header and a colon followed by a block of indented text.

Example:
    Examples can be given using either the ``Example`` or ``Examples``
    sections. Sections support any reStructuredText formatting, including
    literal blocks::

        $ python example_google.py

Section breaks are created by resuming unindented text. Section breaks
are also implicitly created anytime a new section starts.
"""
  • Do not copy the document annotation function definition prototypes, but detailed description of the specific details, explain the specific parameters and return values, etc.
#  不推荐的写法(不要写函数原型等废话)
def function(a, b):
    """function(a, b) -> list"""
    ... ...


#  正确的写法
def function(a, b):
    """计算并返回a到b范围内数据的平均值"""
    ... ...
  • Of function parameters, return values ​​described numpy using standard, as follows
def func(arg1, arg2):
    """在这里写函数的一句话总结(如: 计算平均值).

    这里是具体描述.

    参数
    ----------
    arg1 : int
        arg1的具体描述
    arg2 : int
        arg2的具体描述

    返回值
    -------
    int
        返回值的具体描述

    参看
    --------
    otherfunc : 其它关联函数等...

    示例
    --------
    示例使用doctest格式, 在`>>>`后的代码可以被文档测试工具作为测试用例自动运行

    >>> a=[1,2,3]
    >>> print [x + 3 for x in a]
    [4, 5, 6]
    """
  • Any documentation comments in English, but do not mix in English

  • Documentation Comments are not as long as possible, usually one or two words can make it clear to the situation

  • Module, public class, public methods, can write documentation comments, you should try to write documentation comments

Third, naming convention

1, the module

  • Try to use lowercase module names, initials remain lowercase, try not to use the underscore (unless more than one word, and a small number of cases)
# 正确的模块名
import decoder
import html_parser

# 不推荐的模块名
import Decoder

2, the class name

  • Class names use camel (CamelCase) naming style, capitalized, beginning underscore a private class available
class Farm():
    pass

class AnimalFarm(Farm):
    pass

class _PrivateFarm(Farm):
    pass
  • The related classes and top-level functions in the same module. Unlike Java, a class is not necessary to limit a module.

3, function

  • Function name all lower case, if multiple words separated by underscores
def run():
    pass

def run_with_env():
    pass
  • Private function before the function adds an underscore _
class Person():

    def _private_func():
        pass

4, the variable name

  • Try to lowercase variable names, if multiple words separated by underscores
if __name__ == '__main__':
    count = 0
    school_name = ''
  • Constant all-uppercase, separated if multiple words, use underscores
MAX_CLIENT = 100
MAX_CONNECTION = 1000
CONNECTION_TIMEOUT = 600

5, Constant

  • Constant use uppercase names separated by an underscore
MAX_OVERFLOW = 100

Class FooBar:

    def foo_bar(self, print_):
        print(print_)

Guess you like

Origin www.cnblogs.com/cmd61/p/11123002.html