Python Common PEP8 Coding specifications and recommendations

Source: Internet
Author: User
Tags class definition function definition

Code Layout indentation
    • 4 spaces for each level of indentation.
    • Use vertical implicit indentation in parentheses or use hanging indents.

EXAMPLE:

# (vertical implicit indentation) Align Left parenthesis foo = long_function_name (Var_one, Var_two, Var_three, Var_four)# (hanging indent) The general situation is only one more layer of 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 , separated from subsequent statements block def long_function_name(Var_one, Var_two, Var_three, Var_four): Print (Var_one)# closing parenthesis fallback my_ list = [ 1, 2, 3, 4, 5, 6,]result = some_function_that_takes_arguments ( ' A ', ' B ', 
                    
                      ' C ', 
                     ' d ', ' e ', ' f ',)   
                             

Error Demonstration :

# when no vertical alignment is used, the first row cannot have parameters. Foo = Long_function_name (Var_one, Var_two, Var_three, var_four) # parameter and subsequent code block indentation cannot be distinguished. def long_function_name (Var_one, Var_two, Var_three, Var_four): Print (var_one) # right parenthesis not fallback, Not recommended my_list = [1, 2, 3, 4, 5, 6,]result = Some_function_that_takes_ Arguments ( ' a ',  ' B ',  ' C ',  ' F ', "    
Maximum line width
    • Maximum line width per line not exceeding 79 characters
    • Normal continuation can use a back slash
    • The backslash is not required to continue in parentheses.

EXAMPLE:

# Continue without parentheses, using backslashesWith 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 ())# Continue line in parentheses, try to continue after operatorClassRectangle(BLOB):Def__init__(Self, width, height, color=' Black ', Emphasis=none, highlight=0):if (width = =0and height = = 0 and color = = ' red ' and emphasis = = ' strong ' or Highlight > : ra Ise 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))  
                                        
Blank Line
    • Two lines of blank lines are used to split the definition of top-level functions and classes
    • A single blank row is used to split a method in a class definition

EXAMPLE:

# 类的方法定义用单个空行分割,两行空行分割顶层函数和类的定义。class A(object): def method1(): pass def method2(): passdef method3(): pass
Module Import
    • Each module that you import should be in separate rows
    • The import order is as follows: (there is a blank line split between each module type import, the order of modules inside each group is sorted by the first letter of the module)
      • Standard library
      • Related third-party libraries
      • Local library

EXAMPLE:

# 按模块首字母排序导入, 依此递推import activeimport adidasimport create

Error Example :

# 一行导入多模块import sys, os, knife# 不按首字母导入import createimport activeimport beyond
String
    • Single and double quotes work the same, but must be guaranteed to exist, and cannot be used in a mixture.
      (It is suggested that the sentence use double quotation marks, the word using single quotation marks, but not mandatory.)

EXAMPLE:

# 单引号和双引号效果一样name = ‘JmilkFan‘name = "Hey Guys!"
Spaces in expressions and statements
    • Avoid spaces inside 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 :

if x == 4 : print x , y ; x , y = y , x
    • Cannot have spaces before the opening parenthesis of a function call

EXAMPLE:

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

Error Example :

spam (1)dct [‘key‘] = lst [index]
    • Cannot add multiple spaces before or after an assignment such as alignment

EXAMPLE:

1y = 2long_variable = 3

Error Example :

x             = 1y             = 2long_variable = 3
    • Place a space on either side of the binary operator
      • Compound operator involving = = (+ =,-=, etc.)
      • Comparison operators (= =, <, >,! =, <>, <=, >=, in, not in, are, is not)
      • Logical operator (and, or, not)

EXAMPLE:

or b# 括号内的操作符不需要空格name = get_name(age, sex=None, city=Beijing)
Comments
    • Comment Block
      Comment Blocks are usually applied before the code and are indented the same as the code. Each line starts with ' # ', and there is a single space behind #.

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 comments (should avoid unnecessary comments)

EXAMPLE:

1 # Compensate for border
    • Document string

EXAMPLE:

# 多行文档, 首行首字母大写,结尾的 """ 应该单独成行"""Return a foobangOptional plotz says to frobnicate the bizbaz first."""# 单行的文档, 结尾的 """ 在同一行。"""Return a foobang"""
Naming rules
    • Package and Module Name:
      Package and module names should be short, all in lowercase letters, and multiple letters can be connected using a single underline.

    • Class Name:
      Follow the hump naming

class MyClass(object):    pass
    • Global variable Name:
      The global variable name should be used only within the module as far as possible, and for modules that might be imported using statements, from moduleName import variableName a mechanism should be used __all__ to prevent global variables from being imported by other modules, or to prefix the global variable names with a front-facing underline.

EXAMPLE:

‘name‘
    • Name of function
      The function name should be the all-lowercase concave hump rule.

EXAMPLE:

‘‘
    • Constant name
      Constants are expressed in all uppercase and concave hump rules, usually defined in module shelf

EXAMPLE:

‘‘TOTAL = 1
    • Method name and instance variable
      • Non-public method and instance variable start with front underline
      • There may be times when you want to avoid naming conflicts with subclasses, using two front-facing underscores
        It is important to note that if the property name of Class Foo is a property that cannot be accessed in a way that a __a Foo.__a persistent user can Foo._Foo__a access, the double-front underscore is usually used only to avoid naming conflicts with the properties of the base class.
Programming recommendations
    • The comparison of None with is or is not, and do not use = =

    • Use is instead of 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 an identifier, which is more appropriate for callbacks and string representations
# Yesdef f(x): return 2*x# Nof = lambda x: 2*x
    • Exception classes should inherit from exception, not baseexception

    • Used in Python 2 raise ValueError(‘message‘) insteadraise ValueError, ‘message‘

    • (Consider compatibility with Python3 and the convenience of continuation)

    • When catching an exception, try to indicate the specific exception, try not except Exception to, should catch what problem , not the problem occurs

EXAMPLE:

# Yes (捕获具体异常)try:    import platform_specific_moduleexcept ImportError:    platform_specific_module = None# No (不要全局捕获)try: import platform_specific_moduleexcept: platform_specific_module = None
    • The code in the try/except clause should be as small as possible to prevent other errors from being masked out

EXAMPLE:

# Yestry:    value = collection[key]except KeyError:    return key_not_found(key)else: return handle_value(value)# Notry: return handle_value(collection[key])except KeyError: # 可能会捕捉到 handle_value()中的 KeyError, 而不是 collection 的 return key_not_found(key)
    • The function or method should explicitly return none when there is no return value
# Yesdef foo(): return None# Nodef foo(): return
    • Use a string method instead of a 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() replace string slices to check prefixes and suffixes
      startswith()and endswith more concise to reduce errors

EXAMPLE:

# Yesif foo.startswith(‘bar‘):# Noif foo[:3] == ‘bar‘:
    • Use isinstance() A comparison of object types instead

EXAMPLE:

# Yesif isinstance(obj, int):# Noif type(obj) is type(1):
    • The bool of an empty sequence type object is False:
# Yesif not seq:   passif seq: pass# Noif len(seq): passif not len(seq): pass
    • Do not use = = for bool Comparisons
# Yesif greeting:   pass# Noif greeting == True passif greeting is True: # Worse pass
Copyright NOTICE: Reprint Please specify the source Jmilkfan_ Fan Gui: Http://blog.csdn.net/jmilk 53996580

Python Common PEP8 Coding specifications and recommendations

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.