Python coding specifications)

Source: Internet
Author: User
Tags export class

The encoding conventions provided in this document apply to Python that forms a standard library in major Python releases.CodeFor more information, see the C code style guide in Python C implementation.

This document is adapted from Guido's original article "Python Style Guide" and added some content from Barry's style guide. Where there is a conflict, the style rules of the Guide should be consistent with the intent of this pep ). This pep is still unfinished (in fact, it may never be completed ).

Consistency is important in this style guide. Consistency within a project is more important. Consistency within a module or function is the most important. But the most important thing is: Know When the inconsistency will occur-sometimes there is no implementation style guide. When you are confused, use your best judgment to look at other examples and decide how to look better. I am not ashamed to ask!

There are two good reasons to break an established rule:

(1) When this rule is applied, the Code may become less readable, even if someone is used to reading the code according to this rule.

(2) Breaking the rules to be consistent with the surrounding code (perhaps because of History), although this is also a good opportunity to clear other confusions (real XP style ).

Code Layout

Indent

Use the default value of Python-mode in Emacs: four spaces and one indent level. For really old code, you do not want to create confusion, you can continue to use the 8-space tab (8-space tabs ). Emacs Python-mode automatically discovers the main indentation level in the file, and sets the indent parameter accordingly.

Tab or space

Do not mix tabs and spaces. The most popular Python indent method is to use only spaces, followed by only tabs. Code mixed with tabs and space indentation will be converted to use only spaces. (In Emacs, select the entire buffer and Press ESC-X to remove tabs .) When the python command line interpreter is called, The-T option can be used to warn against the combination of tabs and spaces in the Code. When the-TT option is used, the warning will become an error. These options are highly recommended.

For new projects, we strongly recommend that you only use spaces instead of tabs. Many editors have features that make it easy to implement (in Emacs, check that indent-Tabs-mode is nil ).

Maximum length of a row

There are still many devices around it that are limited to 80 characters per line: And the window is limited to 80 characters. Make it possible to place multiple windows side by side. Using the default folding method on these devices looks ugly. Therefore, limit all rows to a maximum of 79 characters (Emacs must accurately limit the row length to 80 characters), and discharge large pieces of text (document strings or comments) to the order ), we recommend that you set the length to 72 characters.

The preferred way to fold long rows is to use parentheses, square brackets, and row continuation in curly brackets supported by pyhon. If needed, you can add an extra pair of parentheses around the expression, but sometimes it looks better to use a backslash to confirm that the continuation row is properly indented.

The Python-mode of Emacs must be correct. Some examples:

#! Python

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)

Empty row

Use two blank lines to separate top-level functions and class definitions. Use a single blank line to separate methods in the class. Additional blank lines can be used to (conservatively) separate groups composed of related functions, empty rows can be omitted in the middle of a group of related single sentences. (For example, a set of dummy elements ).

When empty rows are used to define the segmentation method, there must be an empty row between the 'class' row and the first method definition. Exercise caution when using empty rows in a function to represent a logical section. Python accepts the contol-l (I .e. ^ L) Tab character as a space: Emacs (and some printing tools) and regards this character as a page delimiter. Therefore, in your file, you can use them to pagination related fragments.

Encoding

The code in the python Core Release must always use ASCII or Latin-1 encoding (also known as ISO-8859-1), and files that use ASCII do not have to have encoded cookies, latin-1 is used only when the comment or document string involves the author's name Latin-1:

In addition, using the \ x escape character is the preferred method to include non-ASCII (non-ASCII) data in a string.

Some files in the test suite used as the pep 263 implementation code are exceptions.

Import

Import (imports) in a separate row, for example:

No: Import sys, OS

Yes: Import sys

Import OS

But this is also possible:

From types import stringtype, listtype

Imports is usually placed at the top of the file, only after the module comments and document strings, before the global variables and constants of the module. Imports should be sequentially grouped:

1. Import the standard library (imports)

2. Import the relevant main package (major package) (that is, all email packages will be imported later)

3. Import specific applications (imports)

You should place an empty line between each group of imports. Relative imports are not recommended for internal package imports, and absolute paths of all imports should be used.

When importing a class from a module that contains the class, you can generally write it as follows:

From myclass import myclass

From Foo. Bar. yourclass import yourclass

If this write causes a local Name Conflict, write

Import myclass

Import Foo. Bar. yourclass

Use "myclass. myclass" and "foo. Bar. yourclass. yourclass"

Spaces in expressions and statements

Guido does not like spaces in the following places:

Placed next to parentheses, square brackets, and curly brackets, for example: "spam (HAM [1], {eggs: 2 })". Always write it as "spam (HAM [1], {eggs: 2 })".

Followed by commas, semicolons, or colons, such:

"If x = 4: Print X, Y: X, Y = Y, X ". Always write it

"If x = 4: Print X, Y: X, Y = Y, X ".

Close to the open parenthesis (Open Parenthesis) in the parameter list of function calls, for example, "spam (1 )". Always write it as "spam (1 )".

Prefixed to the index or slice before the opening brackets, for example:

"Dict ['key'] = list [Index]". Always write it as "dict ['key'] = list [Index]".

More than one space is used to side the value assignment (or other) operator with other operators, such:

#! Python

X = 1

Y = 2

Long_variable = 3

Always write it

#! Python

X = 1

Y = 2

Long_variable = 3

(Don't argue with him about any of the above-Guido has been in this style for more than 20 years .)

Other suggestions

Always place a space on both sides of these binary operators: Value assignment (=), comparison (=, <,> ,! =, <>,<=, >=, In, not in, is, is not), Boolean (and, or, not ).

Insert spaces around Arithmetic Operators in your opinion. Always keep the spaces on both sides of the binary operator consistent.

Some examples:

#! Python

I = I + 1

Submitted = submitted + 1

X = x * 2-1

Hypot2 = x * x + y * y

C = (a + B) * (a-B)

C = (a + B) * (a-B)

Do not use spaces around the '=' sign used to specify the keyword parameter or default parameter value. For example:

#! Python

Def complex (Real, imag = 0. 0 ):

Return magic (r = real, I = IMAG)

Do not write multiple statements on the same line:

No: If Foo = 'blah': do_blh_thing ()

Yes: If Foo = 'blah ':

Do_blah_thing ()

No: do_one (): do_two (): do_three ()

Yes: do_one ()

Do_two ()

Do_three ()

Note

Comments inconsistent with codes are worse than those without comments. When the code is modified, the comments are always updated first! A comment should be a complete sentence. If a comment is a phrase or sentence, the first letter should be in upper case unless it is an identifier starting with a lowercase letter (do not change the upper case of the identifier ).

If the comment is short, it is best to omit the end. A comment block usually consists of one or more paragraphs composed of a complete sentence. Each sentence should end with a full stop. You should use two spaces after the end of the sentence to make Emacs's line breaking and filling work consistent.

When writing in English, Word breaks and spaces are available. Python for non-English countriesProgramClerk: please write your comments in English unless you are 120% sure that the Code will not be read by people who do not understand your language.

Comment Block

The comment block is usually used with some (or all) Code and has the same indentation level as the code. Each line in the comment block starts with '#' and a space (unless it is the indent text in the comment ). The paragraphs in the comment block are separated by rows that contain only a single. It is recommended that the upper and lower sides of the comment block be surrounded by a blank line (or a comment on a new function definition segment under the two rows above ).

Intra-row comment

Comments in a row are comments in the same line as statements. Comments in a row should be used with caution. Comments in a row should be separated by at least two spaces and statements. They should start with '#' and a single space.

X = x + 1 # increment x

If the meaning is clear, in-line comments are unnecessary and should be removed. Do not write as follows:

X = x + 1 # increment x

X = x + 1 # compensate for border

But sometimes, this is helpful:

X = x + 1 # compensate for border

Document string

We should always follow the prepared document string Convention pep 257 [3]. Compile document strings for all public modules, functions, classes, and methods. Document strings are not necessary for non-public methods, but you should have a comment describing what this method does. This comment should be followed by the line "def.

Pep 257 describes the conventions of good document strings. Note that the "at the end of a multi-line document string should be a separate line, for example:

"" Return a foobang

Optional plotz says to frobnicate the bizbaz first.

"""

The document string at the end of a single line can also be the same line.

Version note

If you want to include the Miscellaneous (crud) of the RCS or CVS in your source file, do the following.

#! Python

_ Version _ = "$ revision: 1. 4 $"

# $ Source: e:/cvsroot/python_doc/pep8. TXT, V $

This line should be included after the module's document string. Before all the code, use a blank line to split up and down.

Naming Conventions

The naming conventions of the python library are a bit confusing, so we will never make them completely consistent, but there are still accepted naming rules. New modules and packages (including third-party frameworks) must comply with these standards, but it is preferred to maintain internal consistency for existing inventory in different styles.

Description: naming style.

There are many different naming styles. The following helps identify the naming styles in use, independent of their functions. The following naming styles are well known:

B (single lowercase letter)

B (single capital letter)

Lowercase (lower case)

Lower_case_with_underscores (lower case with underline)

Uppercase (uppercase)

Upper_case_with_underscores (uppercase with underline)

Capitalizedwords (or capwords, camelcase) is named because words can be separated from uppercase and lowercase letters. This is sometimes treated as studlycaps.

Mixedcase (unlike capitalizedwords, the first letter is lower-case !)

Capitalized_words_with_underscores (uppercase letters with underlines) (ugly !)

There is also a style that aggregates related names with short special prefixes. This is not commonly used in Python, but it should be mentioned out of integrity. For example, the OS. Stat () function returns a tuples, and its elements are traditionally named st_mode, st_size, st_mtime, and so on.

All public functions in the X11 library start with X. (In Python, this style is generally considered unnecessary because attribute and method names are prefixed with objects, while function names are prefixed with module names .)

In addition, the following special forms of leading or ending with underlines are accepted (these can usually be combined with any habits ):

_ Single_leading_underscore (leading by a single underline): weak "internal use" sign. (For example, "from M import *" does not import objects starting with the following line ).

Single_trailing_underscore _ (ending with a single underline): Used to avoid conflicts with Python keywords, for example, "tkinter. toplevel (master, class _ = 'classname ')".

_ Double_leading_underscore (Double underline): The class private name starts from Python 1.4.

_ Double_leading_and_trailing_underscore _: the "magic" object or attribute exists in the user-controlled namespace, such as _ init _, _ import _, or _ file _. Sometimes they are defined by the user to trigger a magic behavior (for example, Operator overloading): Sometimes they are inserted by the constructor for your own use or for debugging. Therefore, in future versions, constructors (loosely defined as Python interpreters and standard libraries) may intend to create their own magic attribute lists, user code should usually restrict such conventions as self-use. The user code to be part of the constructor can be used in combination with a short prefix in the next slide line, for example:

_ Bo_magic_attr __.

Description: naming conventions

Name to be avoided. Never use the 'l' (lower case letter El (that is, pronunciation, the same below), 'O' (upper case letter OH), or 'I' (upper case letter eye) variable name that is a single character. In some fonts, these characters cannot be distinguished from numbers 1 and 0. Use 'l' instead of 'l.

Module name

The name of the module should be short and lowercase. Because the module name is mapped to the file name, some file systems are case insensitive and the long name is truncated. It is important to select a short module name, which is not a problem on UNIX, but it may be a problem when the code is uploaded to Mac or windows.

When an extension module written in C or C ++ has a high-level (for example, object-oriented) interface that is accompanied by a python module, the C/C ++ module has an underscore (for example: _ socket ). The Python package should be a short, all lowercase name without any underscores.

Class Name

Almost unexpectedly, the class name uses the capwords convention. The internal class is added with a leading underline.

Exception name

If the module defines a single exception for all situations, it is usually called "error" or "error ". It seems that the built-in (extended) module uses "error" (for example, OS. Error), while the python module usually uses "error" (for example, xdrlib. Error ). The trend seems to be the tendency to use capwords exception names.

Global variable name

(Let's pray that these variables only make sense within one module)

These conventions are the same as those in functions. The module is designed to be used through "from M import *". It must use an underscore as the prefix of global variables (and internal functions and classes) to prevent it from being exported (exporting ).

Function Name

The function name should be in lower case. It may use underlined words to increase readability. Mixedcase is only allowed for context (such as threading. py) That is dominant in this style to maintain backward compatibility.

Method Name and instance variable

This section is basically the same as the function: usually use lower-case words. If necessary, separate them with underscores to increase readability. Only use a leading underline for internal methods and instances that do not intend to serve as the public interface of the class. Python does not force this requirement: It depends on whether the programmer complies with this Convention.

Use two leading underlines to indicate private class names. Python connects these names and class names together:

If the class Foo has an attribute named _ A, it cannot be accessed with Foo. _. (Stubborn users can still get access through Foo. _ Foo _ .)

The double-leading underline is used only to avoid name conflicts between attribute names in classes containing subclasses.

Inherited Design

Always determine whether methods and instance variables in a class should be made public. In general, never disclose data variables unless you implement only records, people almost always prefer to give a function as a class interface (some developers of Python 2.2 do very well in this regard ).

Similarly, determine whether your attributes are private. The difference between private and non-private is that the template will never be valid for the original class (export class), while the latter can. You should have designed your class with inheritance in your brain. Private attributes must have two leading underscores (_), no post underscores (_), and non-public attributes must have a leading underline (_) and no post underline, common attributes do not contain leading or trailing underscores unless they conflict with reserved words. In this case, a single post underline is better than a front or chaotic spelling, for example, class _ is better than Klass.

The last point is somewhat controversial: If you prefer Klass compared to class _, this is just a consistency problem.

Design Recommendations

Comparison of a single element (singletons), for example, none should always be done using: 'is' or 'is not. When you mean "if X is not none", be careful when writing "If X. For example, if you test whether a variable or parameter with the default value of none is set to another value, the value may be false in the Boolean context!

Class-based exceptions are always better than string-based exceptions. Modules and packages should define specific base exception classes in their own domains, and the base class should be a subclass of the built-in exception class. It also always contains a document string of the class. For example:

#! Python

Class messageerror (exception ):

"" Base class for errors in the email package. """

Use the string method (methods) to replace the string module unless it must be backward compatible with versions earlier than Python 2.0. The string method is always very fast, and uses the same API (application interface) as the Unicode string to avoid slicing the string when checking the prefix or suffix. Use startswith () and endswith (), because they are clear and have fewer errors. For example:

No: If Foo [: 3] = 'bar ':

Yes: If Foo. Startswith ('bar '):

The exception is if your code must work in Python 1.5.2 (but we hope it will not happen !), The comparison of object types should always replace the direct comparison type with isinstance (), for example:

No: If type (OBJ) is type (1 ):

Yes: If isinstance (OBJ, INT ):

When checking whether an object is a string, remember that it may also be a unicode string! In Python 2.3, STR and Unicode, there are common base classes, basestring, so you can do this:

If isinstance (OBJ, basestring ):

The stringtypes type is defined in the python 2.2 type module. For example:

#! Python

From types import stringtypes

If isinstance (OBJ, stringtypes ):

In Python 2.0 and 2.1, you should do this:

#! Python

From types import stringtype, unicodetype

If isinstance (OBJ, stringtype) or \

Isinstance (OBJ, unicodetype ):

The fact that the empty list is false is used for the sequence (string, list, And tuples), so "if not seq" or "If seq" is greater than "If Len (SEQ) "or" If not Len (SEQ. Do not rely on meaningful trailing spaces when writing string text. This rear space is visually unrecognizable, and some editors (especially recently, reindent. py) will trim them. Do not use = to compare the Boolean value to determine whether it is true or false (the Boolean value is added in pythn 2.3)

No: If greeting = true:

Yes: If greeting:

No: If greeting = true:

Yes: If greeting:

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.