PYTHON-PEP8 Coding Specification

Source: Internet
Author: User
Tags instance method

PEP8 Coding Specification

This blog is a translated version of PEP8
https://my.oschina.net/u/1433482/blog/464444

Divided into 7 main parts
    • It is important to keep the consistency of the code because it must read more code than write code during the development process.
1. Code layout
    • Indent: Four spaces

    • Multi-parameter hanging or vertical indentation in the method: Select line break in the IDE at the end of the line??? , and two more spaces in the next line to avoid conflicting with the next level of statements

    • Multi-conditional connection in if: basically the same as the above multi-parameter

    • Space or Tab selection: Use spaces in the IDE, automatically using spaces as line breaks, if you are editing in Vim, use a space to maintain consistency

    • Maximum line width: The maximum line width for all rows is 79 characters, and if it is text (such as comments), the maximum is 72 characters

    • Blank line: 1. Normal use, as the split logic fast, do not use too many empty lines; 2. Use two lines in a row between the top-level function and the definition

    • File encoding considerations: Py2, the default is ASCII encoding, and py3 is UTF8 encoding, with the py2, so try to avoid the appearance of Chinese, keep ASCII, or the provisions of the code for UTF8???

    • Import of standard library or normal library: 1. Import a library in a separate row; 2. The import is always at the top of the file, after the module comments and document strings, before the module global variables and constants; 3. Import Order: Standard library, third-party library, local library. There should be a blank line between imports; 4. Try to use absolute path import???

2. String references
    • Double quotes in Python are the same as single-quote strings, and try to avoid writing backslashes in the string "
3. Spaces in expressions and statements
    • Cases where spaces cannot be used: 1. in parentheses; 2. Comma, colon, semicolon, 3. Index slice operator before and after colon??? ; 4. The function name is between the brackets; 5. The list name is between the brackets; 6. The operators with higher precedence are around, such as *;7. The default parameter assignment operator in the method; 8.

    • To use a space: 1. Two-dollar operator or so;

    • The colon is not usually preceded by a

    • Avoid using '; ' as a connection to two statements, try not to write two statements on one line

4. Notes
    • When updating the code, the comments are updated first, and the comments are not as bad as the comments.

    • Note Blocks are written in # and each row is separated by a #

    • Paragraphs within a comment block are split with rows containing only a single ' # '

    • Document strings, used in public modules, functions, classes, and methods, must be written on

    • ' # ' followed by a space

5. Version label
    • If you must include Git, Subversion, CVS, or RCS crud information in the source file, after the module's document string , before any other code , use a blank line up and down
__version__ = "$Revision$"# $Source$
6. Naming conventions
    • Preceded by a single underline: 1. Weak internal flag: From M import objects not imported

    • There is a single underline at the back: 1. Avoid conflicts with keywords

    • There are double underscores in front: 1. When a class is named, it triggers a name reorganization.

    • Avoid using the name: 1. ' I ', lowercase i;2. ' I ', capital i;3. ' O ', capital O;

    • Module name, package name: module name all lowercase, with underline connection; package name is lowercase but not underlined

    • Class Name: Capword named, Pascal Style, first letter capitalized

    • Exception Name: Add error after class name

    • Global variable name: variable as far as possible only inside the module, contract similar functions. For modules that are designed to be used from the "from M import", use the all mechanism to prevent global variables from being imported, or add a front underline to the global variable.

    • Function Name: lowercase, add underline if necessary

    • function and Method Parameters: Instance method The first argument is ' self '. The first parameter of a class method is ' CLS '.

    • Constant name: uppercase and underlined

    • Inheritance naming: Public properties should not have a leading underscore.

If you expose property names and reserved keyword conflicts, you can add a post-underline

Simple public data properties, preferably only the name of the property, there is no complex access/modification method, Python's property provides a good encapsulation method. D. If you do not want the attributes to be used by subclasses, consider naming them with two pre-underlined (no post-underline).

7. Recommendations in programming
    • + Try to write as. Join ()

    • The value of none is compared with is,is not instead of = =

    • The exception class inherits from exception, not baseexception.

    • Python2 "Raise ValueError (' message ')" instead of "raise ValueError, ' message '"

    • When catching an exception, try to indicate the specific exception instead of the empty "except:" clause

    • Python 2.6 is recommended to display the binding exception name with AS

try:    process_data()except Exception as exc:    raise DataProcessingFailedError(str(exc))
    • The function or method should explicitly return none when it is not returned.

    • Use a string method instead of a string module.

    • Use. StartsWith () and. EndsWith () instead of string slices to check for prefixes and suffixes

# Yesif foo.startswith(‘bar‘):# Noif foo[:3] == ‘bar‘:
    • Use Isinstance () instead of object type comparisons:
# Yesif isinstance(obj, int):# Yesif isinstance(obj, basestring):# 字符串类型# Noif type(obj) is type(1):
    • For a sequence (string, list, tuple), the empty sequence is false:
# Yesif not seq:   passif seq:   pass# Noif len(seq):   passif not len(seq):   pass
    • Do not have a large trailing space behind the string.

    • Do not use = = for Boolean comparisons

# Yesif greeting::   pass# Noif greeting == True   passif greeting is True: # Worse   pass

PYTHON-PEP8 Coding 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.