PEP8 Python Coding Specification Collation

Source: Internet
Author: User

(reprinted from http://blog.csdn.net/kellyseeme/article/details/50644893) 1, Code layout design 1.1 indent

A, use four spaces to indent

B, the line can be used when the backslash, the best way is to use the square brackets, when using a backslash, the backslash after the direct carriage return, there can be no space exists

The better practice is as follows:

Alignment Start delimiter:

# Aligned with opening delimiter.
Foo = Long_function_name (Var_one, Var_two,
Var_three, Var_four)

Include more indent representations that are the rest of the section:

# more indentation included to distinguish this from the rest.
Def long_function_name (
Var_one, Var_two, Var_three,
Var_four):
Print (Var_one)

Hanging indents should add a level:

# hanging indents should add a level.
Foo = Long_function_name (
Var_one, Var_two,
Var_three, Var_four)

The poor approach is as follows: (the code can also be run)

# Arguments on first line forbidden if not using vertical alignment.-no vertical alignment
Foo = Long_function_name (Var_one, Var_two,
Var_three, Var_four)
# further indentation required as indentation are not distinguishable. (Does not use indentation to represent each level)
Def long_function_name (
Var_one, Var_two, Var_three,
Var_four):
Print (Var_one)

For continuation lines, the indentation of four spaces is optional.

The following options are available:

# hanging indents *may* is indented to other than 4 spaces. Can not be four spaces when hanging indent
Foo = Long_function_name (
Var_one, Var_two,
Var_three, Var_four)

When using the IF statement, if the condition happens to be indented to four spaces, then the indentation of the subsequent statement is also four spaces, which is acceptable, as follows:

No additional indentation:

# No Extra indentation.
if (This_is_one_thing and
that_is_another_thing):
Do_something ()

Add a comment to split indent to make syntax highlighting:

# Add a comment, which'll provide some distinction in editors
# Supporting syntax highlighting.
if (This_is_one_thing and
that_is_another_thing):
# Since Both conditions is true, we can frobnicate.
Do_something ()

Add additional indents to the continuation line:

# ADD Some extra indentation on the conditional continuation line.
if (this_is_one_thing
and that_is_another_thing):
Do_something ()

A pair of parentheses, in which the brackets can be multiple lines in the structure of a multiline, and then the parentheses end in the first non-whitespace position. As follows:

My_list = [
1, 2, 3,
4, 5, 6,
]
result = Some_function_that_takes_arguments (
' A ', ' B ', ' C ',
' d ', ' e ', ' f ',
)

or align the position of the first character to the end, as follows:

My_list = [
1, 2, 3,
4, 5, 6,
]
result = Some_function_that_takes_arguments (
' A ', ' B ', ' C ',
' d ', ' e ', ' f ',
)

1.2 Tab and Space selection

The choice of the tab space can be mixed in python2, but in Python3, only one style is used.

1.3 Maximum line length

The maximum length of a row is 79 characters

When writing a document or a comment, the line length should be controlled at 72 characters.

Backslashes can be used in some cases, for example, when the parameters are long, but cannot be used implicitly when using multiple lines, as in the following 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 ())

Make sure that contiguous rows are separated at the right time, preferably after the operator, not before the operator, as follows:

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 ("Values are%s,%s"%
(width, height))
Blob.__init__ (self, width, height,
Color, emphasis, highlight)

1.4 Blank Line

When the Top level function and class are defined, two lines are empty.

The definition of a method in a class is an empty line.

Use blank lines sparingly in a function to represent related logical segments.

Unrelated functions are separated by a blank line.

1.5 Source file Encoding

Always use UTF-8 encoding in the source file, using ASCLL encoding in Python2.

files, using ASCLL encoding in Python2, using UTF-8 encoding in Python3

1.6 Import

Import often uses a separate line, as follows:

Import OS
Import Sys

Or use the following method:

§from subprocess Import Popen, PIPE

Import is always at the top of the file, after the comments and docstring of the module, before the global variables of the module.

Import can be organized in the following order:

A standard class library import

B Third Party Import

C Local Class library import

After each group is imported, it can be split with a blank line

Put all __all__ related types of declarations after import

It is recommended to use absolute import, which is readable as follows:

Import mypkg.sibling

From mypkg import Sibling

From mypkg.sibling Import Example

For complex package layouts, relative import is also acceptable, mainly when using absolute import when the path is too long, as follows:

From. Import Sibling

From. Sibling Import Example

When importing a class, you can use the following method:

From MyClass import MyClass

From Foo.bar.yourclass import YourClass

When the above syntax causes a local name conflict, it can be written as follows:

Import MyClass

Import Foo.bar.yourclass

and use the MyClass. MyClass "and" Foo.bar.yourclass.YourClass ".

When importing modules, you should avoid the existence of wildcards, as follows:

From <module> Import *

2. String quotation marks

In the case of strings, there is no difference between using double quotation marks or single quotes, mainly because they are mixed to avoid the appearance of backslashes.

3. Use space 3.1 in expressions and statements to avoid the use of spaces

A Avoid using spaces in parentheses, brackets, curly braces

Yes:spam (Ham[1], {eggs:2})

No:spam (ham[1], {eggs:2})

B Do not need a space before the colon, divide well

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

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

C When slicing, avoid using spaces, and in extended slices you must use the same number of spaces as shown below:

Yes:

Ham[1:9], Ham[1:9:3], Ham[:9:3], Ham[1::3], Ham[1:9:]

Ham[lower:upper], Ham[lower:upper:], Ham[lower::step]

Ham[lower+offset:upper+offset]

ham[: Upper_fn (x): Step_fn (x)], ham[:: STEP_FN (x)]

Ham[lower + offset:upper + offset]

No:

Ham[lower + offset:upper + offset]

Ham[1:9], Ham[1:9], Ham[1:9: 3]

Ham[lower:: Upper]

ham[: Upper]

D Do not add a space before the opening parenthesis of the function:

Yes:spam (1)

No:spam (1)

E. Do not add spaces before the brackets

yes:dct[' key '] = Lst[index]

NO:DCT [' key '] = LST [index]

F. Operators around a space, do not seek consistency to add the number of spaces

Yes:

x = 1

y = 2

Long_variable = 3

No:

x = 1

y = 2

Long_variable = 3

3.2 Other recommendations

A Avoid adding white space at any end.

B Left and right left blank in the following operators

Assignment ( = ), augmented assignment ( + =,-= etc), comparisons ( = = , < , > , ! = , <> , <= , >= , in , no in, i S , is isn't), Booleans ( and, or , not)

C If operator precedence is different, be careful to leave whitespace around the operator, especially high-and low-priority

i = i + 1

Submitted + = 1

x = x*2-1

Hypot2 = x*x + y*y

c = (a+b) * (A-B)

No:

I=i+1

Submitted +=1

x = x * 2-1

Hypot2 = x * x + y * y

c = (A + b) * (a)

D When using a function, no spaces are required between the assignment and the default value

Yes:

def complex (Real, imag=0.0):

Return Magic (R=real, I=imag)

No:

def complex (real, imag = 0.0):

Return Magic (r = Real, I = imag)

E. Do not write multiple statements on the same line

Rather not:

if foo = = ' blah ': do_blah_thing ()

For x in Lst:total + = X

While T < 10:t = delay ()

Definitely not:

if foo = = ' blah ': do_blah_thing ()

Else:do_non_blah_thing ()

Try:something ()

Finally:cleanup ()

Do_one (); Do_two (); Do_three (long, argument,

List, like, this)

if foo = = ' blah ': one (); Both (); Three ()

4. Comments

Be sure to modify the comments when you modify the code.

The comment must be in English, preferably a complete sentence, capitalized in the first letter

4.1 Block Notes

Add a comment before a piece of code, adding a space after #, with only one # as the line interval between the paragraphs

# description:module CONFIG.

#

# Input:none

#

# Output:none

4.2-line Comment

When using line annotations, at least two spaces after the end of the code sentence, followed by a space after the beginning of the #

x = x + 1 # Increment X

But sometimes, this is useful:

x = x + 1 # Compensate for border

In the example above, it means not to use invalid annotations, mainly to illustrate their purpose

4.3 Documentation Comments

Add documentation comments to all public modules, functions, classes, and methods, which are written after def.

When making multi-line comments, note that "" "at the end of the time, you must have an exclusive line, as follows:

"" "Return a Foobang

Optional Plotz says to frobnicate the Bizbaz first.

"""

When the document comment is a row, make sure that the start "and" "are on the same line.

5. Naming specification

Use a separate lowercase letter (b)

Use a separate capital letter (B)

Use lowercase letters (lowercase)

Use lowercase letters and underscores (Lower_case_with_underscores)

Use uppercase letters (uppercase)

Use uppercase letters and underscores (upper_case_with_uppercase)

Camel Style (CamelCase): When using abbreviations, uppercase is better than lowercase such as httpserver better than httpserver

Capitalize and use underscores is an ugly way of writing

5.1 Avoiding the use of names

When writing variables, try to avoid lowercase l and capital letter O and capital letter I, mainly because it is easy to confuse 1,0 with numbers.

5.2 Package and module names

The module uses a short, all-lowercase name as much as possible, and if you can add readability, you can use underscores, and Python packages do not recommend underscores, but you can use underscores in extension packages that reference other languages to express the distinction

5.3 Class Name

Class names are primarily followed by capwords conventions, which represent uppercase letters

5.4 Exception Name

The exception is attributed to the class, which also follows the specification of the class name, mainly by adding "Error" to the suffix

5.4 Global variable Name

Global variables are valid only in module classes, and function names are the same

5.5 Method Name

Method names are all lowercase and underscores are optional (used on the basis of increased readability)

5.6 Method variables

Class method The first argument is always self

The static variables of the class method are always CRS

If the argument of a method conflicts with a reserved word, then underline is added to differentiate

5.7 Constants

Constant names are all capitalized and can be split with underscores

6, coding recommendations

Use is or is not when comparing separately, do not use = = to compare.

When implementing the method of comparison, it is best to implement all

__eq__ , __ne__ ,__lt__ , __le__ , __gt__ , __ge__ ), instead of implementing one alone.

The sequence prefix or suffix is checked using startswith () and EndsWith () instead of slices. Like what

Yes:if foo.startswith (' Bar '): Better Than

No:if Foo[:3] = = ' Bar ':

7 use Isinstance () to compare the type of the object. Like what
Yes:if isinstance (obj, int): Better Than
No:if type (obj) is type (1):

PEP8 Python Coding Specification Collation

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.