PEP 8 Python Programming specification

Source: Internet
Author: User
Tags function definition

A code orchestration
    1. Indent. Indentation of 4 spaces (the editor can do this), no tap, no mix of taps and spaces.
    2. The maximum length per line is 79, the line break can use backslashes, preferably with parentheses. The newline point is to hit enter after the operator.
    3. There are two empty lines between the class and the top-level function definition, an empty line between the method definitions in the class, and an empty line between the logically unrelated paragraphs in the function;
Two-document orchestration
    1. Module Content Order: module description and docstring-import-globals&constants-other definitions. The import part, in accordance with the standard, three-party and their own writing in order to discharge, between the empty line.
    2. Do not have multiple libraries in an import, such as import OS, SYS is not recommended.
    3. If you use the From XX import xx Reference library, you can omit the ' module. ', it is possible to have a naming conflict, it is necessary to use import xx.
Use of three spaces

Principles to avoid unnecessary spaces.

    1. Do not add spaces before the various closing brackets.
    2. Do not add spaces before commas, colons, and semicolons.
    3. Do not add a space before the opening parenthesis of the function. such as func (1).
    4. Do not add a space before the opening parenthesis of the sequence. such as list[2].
    5. Add a space around the operator, and do not add spaces in order to align.
    6. The function default argument uses an assignment character that omits spaces left and right.
    7. Do not write multiple statements on the same line, although use '; ' allows.
    8. In a if/for/while statement, you must have a different row even if the execution statement has only one sentence.
Four notes

Principle, the wrong comment is better than no comment. So when a piece of code changes, the first thing to do is change the comment!
Comments must be in English, preferably a complete sentence, the first letter capitalized, after the sentence to have Terminator, the Terminator followed by two spaces, start the next sentence. If it is a phrase, you can omit the terminator.

    1. Block comments, added comments before a piece of code. Add a space after ' # '. Between paragraphs with a line interval of only ' # '. Like what:
      # description:module CONFIG.
      #
      # Input:none
      #
      # Output:none
    2. Line comment, and comment after a sentence. Example: x = x + 1 # Increment X
      But this approach is used sparingly.
    3. Avoid unnecessary annotations.
Five Document description
    1. Write docstrings for all common modules, functions, classes, methods, not common, but can write comments (on the next line of Def).
    2. If docstring to wrap, refer to the following example, see Pep 257

"" "Return a Foobang

Optional Plotz says to frobnicate the Bizbaz first.

"""

Six naming conventions

Principle, the new code must be in the following naming style, the existing library encoding as far as possible to maintain style.

    1. Try to use lowercase letters ' l ', uppercase letters ' O ', and so on to be easily confused.
    2. The module is named as short as possible, using the all lowercase method, you can use underscores.
      3.: Package naming is as short as possible, using all lowercase methods, you cannot use underscores.
    3. The class is named using Capwords, and the classes used inside the module take the _capwords approach.
    4. The exception name uses the Capwords+error suffix method.
    5. Global variables are as effective as possible within the module, similar to static in C. There are two methods of implementation, one is the __all__ mechanism, and the other is the prefix an underscore.
    6. The function name uses all lowercase, and you can use underscores.
    7. The constant name is used in all uppercase, and you can use underscores.
    8. The properties of the class (methods and variables) are named using the all lowercase method, and you can use underscores.
    9. The properties of the class have 3 scopes public, Non-public, and subclass APIs that can be interpreted as the public, private, protected,non-public attributes in C + +, preceded by an underscore.
    10. If the attribute of the class conflicts with the keyword name, the suffix is underlined, try not to use other methods such as thumbnails.
    11. To avoid naming conflicts with sub-class attributes, prefix two is underlined before some properties of the class. For example: Class Foo declared __a, access, only through foo._foo__a, to avoid ambiguity. If the subclass is also called Foo, there is nothing you can do about it.
    12. The first parameter of a class's method must be self, and the first parameter of a static method must be CLS.
Seven coding recommendations
    1. The coding takes into account the efficiency of other Python implementations, such as the high efficiency of the operator ' + ' in CPython (Python), which is very low in Jython, so the. Join () method should be used.
    2. If possible, replace ' = = ' with ' is ' isn't, such as if X is not None to be superior to if X.
    3. With class-based exceptions, each module or package has its own exception class, which inherits from exception.
    4. Do not use bare except,except followed by specific exceptions in the exception.
    5. The code for the try in the exception is as few as possible. Like what:
try:    value = collection[key]except KeyError:    return key_not_found(key)else:    return handle_value(value)

To better than

try:    # Too broad!    return handle_value(collection[key])except KeyError:    # Will also catch KeyError raised by handle_value()    return key_not_found(key)
    1. 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 ':
    2. 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):
    3. Judging the sequence is empty or not empty, there are the following rules
      Yes:if not seq:
      If seq:
      Better than
      No:if Len (seq)
      If not Len (seq)
    4. String do not end with a space.
    5. Binary data determines how to use if boolvalue.

PEP 8 Python Programming specification

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.