Python code specification for Python

Source: Internet
Author: User
Tags naming convention uppercase letter

PEP Introduction

PEP is the abbreviation for Python enhancement proposal, which is the meaning of the Python enhancement proposal.
Python's code style is described by pep 8. This document describes all aspects of the Python programming style. Under the conditions of this document, Python code written by different programmers can maintain a similar style to the maximum extent possible. This makes it easy to read and communicate easily between programmers.

Naming conventions with different naming styles

There are many different naming styles. The following helps to identify the naming style being used, which is independent of their role.

    • lowercase string (lowercase)
    • Underlined lowercase string (lower_case_with_underscores)
    • Uppercase string (uppercase)
    • Underlined uppercase string (upper_case_with_underscores)
    • The first capitalized word string (capitalizedwords) (or capwords, CamelCase, because its letter looks patchwork, so this name)
      Note: Using abbreviations in capwords, you need to capitalize all the letters of the abbreviation. So Httpservererror is better than Httpservererror.
    • Mixed case String (mixedcase) (unlike the first capitalization string, the first character is lowercase!) )
    • An underlined initial capitalization string (capitalized_words_with_underscores) (ugly!) )
Avoid the use of names

You must not use the letter ' l ' (lowercase letter L), ' O ' (uppercase Letter O '), ' I ' (uppercase letter of I)) as a variable name for a single character.
In some fonts, these characters cannot be distinguished from the numbers 1 and 0. When you want to use ' l ', replace it with ' l '.

Package and module names (packages and modules Names)

The module name should be a short, all lowercase name. You can use underscores in the module name to improve readability. The Python package name should also be a short, all-lowercase name, although it is not recommended to use underscores.
Because module names are mapped to filenames, some file systems are case insensitive and truncated, so it is important to choose a module name that is fairly short-this is not a problem on UNIX, but it can be a problem when migrating code to Mac, Windows, or DOS.
When an extension is written in C or C + +, there is an accompanying Python module that provides a higher level (for example, more object-oriented) interfaces with a leading underscore (such as: _socket) for A/C + + module name.

Class name (Names)

With almost no exceptions, the class name uses the conventions of the first capitalized word string (capwords). The internally used class uses an additional leading underscore.

Exception name (Exception Names)

Because the exception should be a class, the class naming convention also applies to exceptions. However, you should add the suffix "error" to the exception name (if the exception is indeed an error).

Global variable name (Globals Variable Names)

(We want these variables to be used only within a module).
For modules that are designed to be used from the "from M import", use the all mechanism to prevent global variables from being exported, or use the old conventions to add a leading underscore to the class global variable (you may want to indicate that these global variables are restricted to use within the module, "module Non-public ").

Add:
In the Python module, you can use the all function to define this module as other variables that reference your own module imports:

__all__ = [‘bar‘, ‘baz‘]waz = 5bar = 10

When an import * declaration is used in another module, the WAZ and bar variables are not imported, and all can hide the default values that you do not want to import.

function name (functions Names)

The function name should be lowercase, and if necessary, use an underscore to separate the words to increase readability.
Mixed case (mixedcase) is only allowed for contexts where this style has prevailed (for example, threading.py) in order to maintain backward compatibility.

Parameters for functions and methods (function and method arguments)

The method of the instance is always the first argument with ' self '.
For a method of a class, always use ' cls ' to do the first argument.
(if the function's parameter name conflicts with a reserved keyword, an underscore after the parameter name is better than an abbreviated, misspelled spelling.) So "Print_" is better than "prnt". Perhaps using synonyms to avoid conflict is better)

add:
Python class, the first parameter of the normal method needs to be self, which represents a specific instance itself; If you use Staticmethod, you can ignore Instead of using this method as a normal function, for Classmethod, its first argument is not self, which is the CLS, which represents the class itself.

>>> class A(object): def foo1(self): print "Hello",self @staticmethod def foo2(): print "hello" @classmethod def foo3(cls): print "hello",cls>>> a = A()>>> a.foo1() #最常见的调用方式,但与下面的方式相同Hello <__main__.A object at 0x9f6abec>>>> A.foo1(a) #这里传入实例a,相当于普通方法的selfHello <__main__.A object at 0x9f6abec>>>> A.foo2() #这里,由于静态方法没有参数,故可以不传东西hello>>> A.foo3() #这里,由于是类方法,因此,它的第一个参数为类本身。hello <class ‘__main__.A‘>>>> A #可以看到,直接输入A,与上面那种调用返回同样的信息。<class ‘__main__.A‘>
Method name and instance variables (method Names and Instance Variables)

Use the function naming convention: Lowercase words, which, if necessary, can be used to separate words to increase readability.
Only a leading underscore is applied to the Non-public method and the instance variable.

To avoid naming conflicts with subclasses, use two leading underscores to trigger Python's naming reorganization rules.
Python uses the class name to reshape these names: If the class Foo has a property named A, it cannot be foo. A access (the persistent user can still get access via foo._foo__a). Typically, a double-leading underscore is used only to avoid name collisions with properties of the base class.

Remember the naming conventions of Python features
    • Public properties should not have a leading underline
    • If you expose property names and reserved keyword conflicts, add a post-underline after your property name
    • Keep in mind that Python provides an easy way for future enhancements, and you should find that simple data attributes require additional functional behavior. In that case, the function implementation is hidden behind the simple Data property access syntax with the attribute (properties).
    • There is no private variable in Python if you encounter a variable that needs to be protected, use lowercase and a leading underscore. But this is only a convention between programmers, to warn that this is a private variable, the external class does not go to access it. But in fact, the external class can still access this variable.
    • X ), preceded by two underscores, is a system-defined variable name that has special meaning for the interpreter. Includes two leading underscores, two post-underline function names, which apply only to special functions such as operator overloading.
Code layout indentation (indentation)

4 spaces for each level of indentation.
Never mix tabs and spaces.
The most popular way to indent a Python is to use only spaces, followed by tabs only. Code that is mixed with tabs and spaces indents is converted to use only spaces. Use the-t option when invoking the Python command-line interpreter to warn against illegal mixed tabs and spaces in your code (warnings). Warning will become an error when using-TT. These options are highly recommended.
For new projects, it is strongly recommended to use only spaces instead of tabs. Most editors have features that make it easy to implement.

Max line width (Maximum line Length)

Limit the maximum line width of all rows to 79 characters. The preferred way to
collapse long lines is to use the line continuation in the parentheses, brackets (brackets), and braces (braces) supported by Python. If you want, you can add an extra pair of parentheses around the expression, but sometimes using a backslash looks better. Confirm that the continuation line is properly indented.

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("I don‘t think so") Blob.__init__(self, width, height, color, emphasis, highlight)
Blank line (blank Lines)

Divides the definition of the top-level function and class with two lines of empty rows.
The definition of a method within a class is split with a single blank line.
Use caution when using empty rows in a function to represent a logical paragraph.

Import (Imports)
    • Typically, you should import in a separate line:
      Yes:import OS
      Import Sys

No:import sys, OS
But it's also possible:
From subprocess import Popen, PIPE

  • Imports are usually placed at the top of the file, only after the module comments and document strings, before the module's global variables and constants.

  • Imports should be placed in groups in the following order:

  • Import of standard libraries
  • Import of related third-party packages
  • Specific import of local apps/libraries

  • For internal package imports, it is highly deprecated to use relative imports. Always use the absolute path of the package for all imports

  • When you import a class from a module that contains classes, you can usually write this:
    From MyClass import MyClass
    From Foo.bar.yourclass import YourClass
    If this causes a local name conflict, write this:
    Import MyClass
    Import Foo.bar.yourclass
    and use the MyClass. MyClass "and" Foo.bar.yourclass.YourClass "

Spaces in expressions and statements (whitespace in Expressions and statements)
    • close to parentheses, brackets and braces:
      Yes:spam (ham[1], {eggs:2})
      No:spam (ham[1], {eggs:2})
    • close to comma, semicolon, or colon:
      yes:if x = = 4:print x, y; x, y = y, x
      no:if x = = 4 : print x, y; X, y = y, x
    • close to the opening parenthesis of the function call's argument list:
      Yes:spam (1)
      No:spam (1)
    • Close to opening brackets at the beginning of an index or slice (indexing or slicing):
      yes:dct[' key '] = Lst[index]
      no:dct [' key '] = LST [index]
    • Yes:
      x = 1
      y = 2
      long_variable = 3
      No :
      x = 1
      y = 2
      long_variable = 3
Note (Comments)

Comments that are inconsistent with the code are worse than no comments. Always update comments first when the code is modified!
The comment should be a complete sentence. If the comment is a phrase or sentence, the first letter should be capitalized, unless it is an identifier that starts with a lowercase letter (never change the case of the identifier).
If the comment is short, you can omit the end of the period. A comment block is usually made up of one or more paragraphs, which consist of a complete sentence, and each sentence should end with a period.
You should use two spaces after the end of the statement's period (a sentence-ending period).
Python programmers in non-English-speaking Countries: please write your comments in English unless you are 120% confident that the code will never be read by someone who doesn't understand your language.

Comment Block (block Comments)

The comment block is typically applied to some (or all) of the code following it, and has the same indentation level as the code. Each line in the comment block starts with ' # ' and a space (unless it is indented text within the comment).
The paragraphs within the comment block are split with rows that contain only a single ' # '.

Inline comment (line Comments)

Frugal use of in-line annotations.
An in-line comment is a comment on the same line as the statement. In-line annotations should be separated by at least two spaces and statements. They should start with a ' # ' and a single space.
In-line comments are not required, and in fact, if it's obvious, it can be distracting. Do not do this:
x = x + 1 # Increment X
But sometimes, this is beneficial:
x = x + 1 # Compensate for border

Resources

How to use Pylint to standardize Python code styles
PEP 8-style Guide for Python Code

Reprint please indicate the author Jason Ding and its provenance
GitHub Blog Home page (http://jasonding1354.github.io/)
CSDN Blog (http://blog.csdn.net/jasonding1354)
Jane Book homepage (http://www.jianshu.com/users/2bd9b48f6ea8/latest_articles)

Python code specification for Python

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.