Python Code format specification

Source: Internet
Author: User

Current specifications are based on pep-0008

Basic formatting indentation

Indent with 4 spaces

Line width

Try not to exceed 80 characters per line of code

Reason:

    • This is helpful when looking at Side-by-side diff.
    • Easy to view code under the console
    • Too long could be a flawed design
Line break

Python supports line breaks in parentheses. There are two kinds of situations.

    1. The second line indents to the beginning of the parentheses
= Long_function_name (Var_one, Var_two,                         Var_three, Var_four)
    1. The second line indents 4 spaces, applies to the case where the starting parenthesis wraps
Long_function_name (        var_three,        print (var_one) 

With backslash \ wrapping, the two-dollar operator, and so on, + . should appear at the beginning of the line and align with the previous row, . = or indent 4 spaces. Long strings can also be wrapped in this method.

 foo = variable_with_long_name + another_variable + V Ariablesession.query (MyTable). filter_by (id=1). One () This_is_a_very_long (Function_call,  ' with many parameters print < Span class= "Pl-pds" > ' Hello,  '  ' % s %s! % ( ' Harry "< Span class= "Pl-pds" > ' Potter "         

List or tuple of multiple elements, wrapping after starting brackets, 4 spaces in the second line

= [' This was the first    ' Set of items' with ' + more items ' to come ' "This'] 

A compound statement is prohibited, that is, a row contains multiple statements:

# Yesdo_first () Do_second () Do_third ()# Nodo_first ();d o_second ();d o_third (); 

if/for/whileBe sure to change the line:

# Yes' blah': do_blah_thing ()# no' blah': do_blash_thing ()    
Blank Line
    • Two empty lines between the module-level function and the class definition;
    • An empty line between class member functions;
    • Do not use too many contiguous blank lines to differentiate the logical blocks of code
A: "" "This is    a simple docstring.    " "" " __init__ (hello (passhello (%s!  % NamePass        
    • Multiple empty rows can be used to separate multiple sets of related functions
    • A function can use a blank line to separate logically related code
Expression spaces
    • Unary operators do not add spaces
    • On each side of the two-dollar operator, empty one lattice [=,-,+=,==,>,in,is not, and] :
# Yesexp=-1.05i= I+1submitted+=1x= X*2-1hypot2 = x * x + y * yc = (a + b) * (a -B) # noexp = -1.05i< Span class= "pl-k" >=i+1submitted += 1x = x*2 - 1hypot2 = x*x + y*yc = (A+b) * (A-b)     
    • The argument list of the function, , followed by a space
# Yescomplex (pass# nocomplex (Real,pass     
    • In the parameter list of the function, do not add spaces between the default equals sign
# Yescomplex (imag=passcomplex (pass     
    • After opening parenthesis, do not add extra space before closing parenthesis.
# yesspam (ham[= My_list[index]# nospam (ham[= my_list[index]  
    • No extra spaces before the opening parenthesis of a dictionary or List object
# yesdict[' key= List[index]# nodict [' Key= list [index]    
    • Do not use extra spaces for Zishing value statements
33
Comparison
    • Use variable on left, constant in right
    • Do not display a comparison of the pairs True , False
    • Negative comparisons are adopted foo not in bar in the form of, rather thannot foo in bar
    • Use the instance(a, C) type check for the instance, nottype(A) is C
# YesIf method==' MD5': pass if not foo: passif Foo not in bar: PassIf instance (A, C): Pass# N oif ' md5' = = method: passif foo = = False: pass if not foo in  ba R: Passif type (A) is C: pass          
Quotes

Simply put, the natural language uses double quotes, the machine is marked with single quotes, so most of the code should use single quotes

    • Use double quotation marks for natural language"..."
      such as error messages; In many cases Unicode, useu"你好世界"
    • machine identification using single quotes ‘...‘ such as key in Dict
    • Regular Expressions use native double quotesr"..."
    • document characters use three double quotation marks"""......"""
Import statement
    • Import statements should be written in branches
# Yesimport OSimport sys# noimport sys,os# YesPIPE     
    • The import statement should use absolute import
# Yesimport Bar# noimport bar  
    • The import statement should be placed at the head of the file, after the module description and docstring, before the global variable;
    • Import statements should be ordered in order, separated by a blank line between each group
Import OSimport sysimport msgpackimport zmqimport foo   
    • When you import class definitions for other modules, you can use relative imports
Import MyClass
    • If a naming conflict occurs, you can use the namespace
Import Foo.barbar.Bar () Foo.bar.Bar ()
Comment Block Comment

#After the number is empty, the paragraphs are separated by a blank line (the same number is required # )

# block Comment  # block Comment ## block Comment # block comment   
Line Comment

Use at least two spaces and statements to separate, using meaningful annotations

1  # border Bold one  pixel
DocString

The docstring specification is described in detail in PEP 257, where the two points are the most:

    1. All public modules, functions, classes, methods, should be written docstring. Private methods are not necessarily required, but a block comment should be provided after the def to illustrate.
    2. The docstring "" "should have a single line unless this docstring has only one row.
"" "Return a foobarOptional Plotz says to frobnicate the Bizbaz first." " "" " oneline docstring    " ""
Naming conventions
    • Avoid using lowercase letters l(L) , uppercase letters, O(o) or I(i) separate names as a variable to differentiate between numbers 1 and0
    • Packages and modules use all lowercase names and try not to use underscores
    • The class name uses CamelCase a naming style, and the inner class can start with an underscore;
      The contracted abbreviations are left as-is, for example, to use HTTPWriter insteadHttpWriter
    • The function uses an underscore-delimited lowercase name,lowercase_with_underscores
    • When the parameter name and the python reserved word conflict, you can add an underscore at the end and try not to use abbreviations or self-made words
    • Constants are named with an underscore-delimited capitalization,UPPERCASE_WITH_UNDERSCORES
    • Precompiled Regular Expressions:name_re
100Class FooBar:        foo_bar (  

Function and Method arguments:

    • Class methods: As first cls parameter.
    • Instance methods: As first self parameter.
    • Lambdas for properties is the first parameter replaced x with, as in display_name = property(lambda x: x.real_name or x.username) .
Coding
    • File using UTF-8 encoding
    • File header Join #-*-coding:utf-8-*- logo

Python Code format specification

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.