"Go" python--coding specification

Source: Internet
Author: User
Tags arithmetic operators coding standards naming convention string methods


From the Woodpecker community Python Coding Rule
      • ---hoxide first translation dreamingk proofreading release 040724
      • ---xyb re-typesetting 040915
      • ---zoomquiet moinmoin landscaping 050610


Coding style conventions when developing with Python



Source:PEP 008 Style Guide for Python code



Download (Chinese pdf): pythoncodingrule.pdf


    • Further:
      • Google Python Style Guide

      • Pythonstyleguide-soc-style Guide-Python code contributed to Melange

        • Python/python Coding style Guide in translation (Google SOC) Elias's personal homepage

      • Concise Python Programming Specification-Rai Yonghao's programming private office-CSDN Blog

      • Python Development Coding Specification

      • Code like a pythonista:idiomatic Python

1 Introduction
    • The coding conventions given in this document apply to Python code that makes up the standard library in the main Python release. Please refer to the relevant description of the C code style guide in Python's C implementation. This document was adapted from Guido's original Python style guide article. and added some content from the Barry's style guide. Where there is a conflict, the guide's style rules should be consistent with the intent of this pep (that is, when there is a conflict, the Guido style should prevail) This pep may still be unfinished (in fact, it may never end).
Recommendations for consistency


Foolish to use consistency is the devil of ignorance (A foolish consistency is the hobgoblin of Little Minds)

Stupid adherence to consistency is silly!-Zoomq
Consistency is important in this style guide. Consistency within a project is more important. Consistency within a module or function is most important. But most importantly: know when it will be inconsistent-sometimes just No style guidance was implemented. When in doubt,
Use your best judgment. Look at other examples and decide how to look better. And ask ashamed!
Two good reasons to break an established rule:
When this rule is applied, it will cause the code to be less readable, even for someone who is already used to reading the code according to this rule.
Breaking the rules in order to be consistent with the surrounding code (perhaps for historical reasons)
-Although this is also a good opportunity to clear up other clutter (real XP style).
2 Code layout
(Code lay-out)

2.1 Indentation
(Indentation)

The default value of Python-mode using Emacs: 4 spaces for an indentation level. For really old code, you don't want to cause confusion, you can continue to use 8-space tabs. Emacs Python-mode Automatically find the main indentation levels in the file, and set the indentation parameters accordingly.
2.2 Tabs or spaces?
(Tabs or Spaces)

Never mix tabs and spaces. The most popular Python indentation method is to use only spaces, followed by tabs only. Code that mixes tabs and space indentation will be converted to use only spaces. (In In Emacs, select the entire buffer and press ESC-x to remove tabs (untabify).) Use the -t option when calling the python command line interpreter to warn you of illegally mixed tabs and spaces in the code (warnings ). Warnings will become errors when using -tt. These options are highly recommended. For new projects, it is highly recommended to use spaces-only instead of tabs. Many editors Have features that make it easy to implement (in Emacs, make sure indent-tabs-mode is nil).
2.3 maximum line length
(Maximum Line Length)

There are still many devices around that are limited to 80 characters per line; moreover, the limitation of windows to 80 characters makes it possible to place multiple windows side by side. Using the default way of wrapping on these devices looks a bit ugly. Therefore, Please limit all lines to a maximum of 79 characters (Emacs accurately limits lines to 80 characters in length). For large blocks of text (document strings or comments), it is recommended to limit the length to 72 characters. The first choice for folding long lines This is done using line brackets supported by Pyhon, square brackets (brackets), and braces (braces). Continuations can be added around the expression if needed, but sometimes using a backslash looks like Better. Make sure that the continuation lines are properly indented. Emacs' Python-mode does this correctly. Some examples:
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 do n‘t think so"
            Blob .__ init __ (self, width, height,
                          color, emphasis, highlight)
2.4 blank line
(Blank Lines)

The top-level function and class definitions are split with two blank lines, and the definitions of methods within a class are split with a single blank line.
Extra blank lines can be used (sparingly) to split a group of related functions. Blank lines can be omitted in a group of related single sentences. (E.g. a set of dummy implementations)).
When a blank line is used to split the method definition, there must also be a blank line between the 'class' line and the first method definition.
When using blank lines in functions, use caution to indicate an logical logical section. Python accepts contol-L (i.e. ^ L) form feeds as spaces; Emacs (and some printing tools) treats this character as Page separators, so you can use them to paginate related sections in your file.
2.5 encoding
(Encodings) (PEP 263)

Code in the Python core distribution must always use ASCII or Latin-1 encoding (aka ISO-8859-1). Files using ASCII do not need to have a coding cookie. Latin-1 is only used when comments or docstrings are involved The author name is used only when Latin-1 is used; in addition, the \ x escape character is the preferred method for including non-ASCII data in the string. Part of the file as a test suite of the PEP 263 implementation code is an exception.
Kernel supports Unicode since Python 2.4! Use UTF-8 in any case! This is king!
--ZoomQuiet

3 Import
(Imports)

Imports should usually be on separate lines, for example:
No: import sys, os
Yes: import sys
     import os
But this is also possible:
from types import StringType, ListType
Imports are usually placed at the top of the file, only after module comments and docstrings, and before module global variables and constants. Imports should be placed in groups in order.
Imports of the standard library
Import of related major packages (i.e. all email packages are imported later)
Application-specific imports
You should put a blank line between each set of imports.
Relative imports are not recommended for internal package imports. You must use the absolute path of the package for all imports.
When importing a class from a module that contains a class, it can usually be written like this:
from MyClass import MyClass
from foo.bar.YourClass import YourClass
If writing this way causes local name conflicts, then just write it like this
import MyClass
import foo.bar.YourClass
Ie use "MyClass.MyClass" and "foo.bar.YourClass.YourClass"

4 spaces
(Whitespace in Expressions and Statements)

Guido doesn't like spaces in:
"spam (ham [1], {eggs: 2})". Always write this as "spam (ham [1], {eggs: 2})".

Next to parentheses, square brackets, and curly braces, such as: "spam (ham [1], {eggs: 2})". Always write it as "spam (ham [1], {eggs: 2}) ".

"if x == 4: print x, y; x, y = y, x". Always write this as "if x == 4: print x, y; x, y = y, x".

Immediately before a comma, semicolon, or colon, such as:
"if x == 4: print x, y; x, y = y, x". Always write it as "if x == 4: print x, y; x, y = y, x".

Open parenthesis immediately before the parameter list of the function call, such as "spam (1)". Always write it as "spam (1)".

slicing, as in: "dict [‘ key ‘] = list [index]". Always write this as "dict [‘ key ‘] = list [index]".

Immediately before the open bracket at the beginning of the index or slice (slicing? Subscript?), Such as:
"dict [‘ key ’] = list [index]". Always write it as "dict [‘ key ’] = list [index]".

One or more spaces around the assignment (or other) operator to be side-by-side with others, such as:
x = 1
y = 2
long_variable = 3
Always write it as
x = 1
y = 2
long_variable = 3
(Don't argue with any of the above-Guido has developed this style for more than 20 years.)
Other suggestions
(Other Recommendations)

Always put a space around these binary operators: assignment (=), comparison (==, <,>,! =, <>, <=,> =, In, not in, is, is not), boolean Operation (and, or, not).

* Insert spaces around arithmetic operators as you see them. Always keep the spaces on both sides of the binary operator consistent.

Some examples:
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 that specifies keyword parameters or default parameter values, for example:
def complex (real, imag = 0.0):
    return magic (r = real, i = imag)
Don't write multiple statements on the same line.
No: if foo == ‘blah’: do_blah_thing ()
Yes: if foo == ‘blah’:
                 do_blah_thing ()
No: do_one (); do_two (); do_three ()
Yes: do_one ()
         do_two ()
         do_three ()
5 comments
(Comments)

A comment that is inconsistent with the code is worse than no comment. When the code is modified, the comment is always updated first! The comment should be a complete sentence. If the comment is a phrase or sentence, the first letter should be capitalized, unless it starts with a lowercase letter Identifiers (never change the case of identifiers). If the comment is short, it is best to omit the period at the end (period? Pause at the end of the sentence? Can also be a comma,) Comment blocks usually consist of one or more complete Sentences consist of paragraphs, and each sentence should end with a period. You should use two spaces at the end of the sentence and the period to make Emacs' line breaks and padding work coordinate Work, "." Gives a hint on the structure of the document). Hyphenation and spaces are available when writing in English. Python programmers in non-English speaking countries: Please write your comments in English unless you are 120% sure of these The code will not be read by people who do not understand your language.
I just insisted on using Chinese for all comments. When I really want to release the script tool, I think about E text; I must use it in my thoughts every time I develop, and I do n’t use it in E text grammar or words!
-ZoomQUiet

The convention to use a uniform documented comment format is good for good habits and team suggestions! -CodeCommentingRule

5.1 Comment block
(Block Comments)

A comment block is usually used to follow some (or all) code and have the same indentation level as those codes. Each line in a comment block starts with '#' and a space (unless it is indented text within a comment)
Paragraphs within a comment block are separated by lines containing only a single ‘#’. The top and bottom of the comment block are preferably surrounded by an empty line (or two lines above and below, a comment about a new function definition section).
5.2 Inline comments
(Inline Comments)

(inline? Inline? It's better to turn into "inline")
An inline comment is a comment on the same line as the statement. Inline comments should be applied with caution. Inline comments should be separated from the statement by at least two spaces. They should start with ‘#’ and a single space.
x = x + 1 # Increment x
If the semantics are clear, inline comments are unnecessary and should be removed in fact. Don't write like this:
x = x + 1 # Increment x
x = x + 1 # Compensate for border
But sometimes, this is helpful:
x = x + 1 # Compensate for border
6 Documentation
(Documentation Strings)

Conventions for writing good documentation strings (a.k.a. "docstrings") are immortalized in
PEP 257. Should always follow the conventions of written docstrings (aka "docstrings") (? I really don't know how to translate)

Documentation Strings-- Documented characters; In order to cooperate with the use of documentation tools such as pydoc; epydoc, Doxygen, etc., similar to MoinMoin syntax, some characters are agreed to in order to automatically extract and convert articles into meaningful document chapters and other article elements!-Zoomq
Write docstrings for all public modules, functions, classes and methods. The docstring is not necessary for non-public methods, but you should have a comment describing what this method does. This comment should be after the "def" line .
PEP 257 describes good document string conventions. Be sure to note that "" "at the end of a multi-line document string should be on a separate line, for example:

"" "Return a foobang
Optional plotz says to frobnicate the bizbaz first.
"" "
For single-line docstrings, the ending "" "can also be on the same line.
In fact, Python maintains the instructions for all built-in objects using documented coding from its own. \ If you don't believe it, try it often:
        #python
>>> import time
>>> dir (time)
['__doc__', '__file__', '__name__', 'accept2dyear', 'altzone', 'asctime', 'clock', 'ctime', 'daylight', 'gmtime', 'localtime', 'mktime', ' sleep ',' strftime ',' strptime ',' struct_time ',' time ',' timezone ',' tzname ',' tzset ']
>>> help (time.time)
Help on built-in function time in module time:
time (...)
        time ()-> floating point number
        Return the current time in seconds since the Epoch.
        Fractions of a second may be present if the system clock provides them.
7 release notes
(Version Bookkeeping) (I think it's better to call "notebook")

If you want to include the crs of RCS or CVS in your source files, do as follows.
__version__ = "$ Revision: 1.4 $"
    # $ Source: E: /cvsroot/python_doc/pep8.txt,v $
This line should be included after the module's docstring and before all code, separated by a blank line above and below.
For the CVS server working mark, it should be clearly used in the code section. For example, the following version mark should be added after the copyright notice at the beginning of the document:
# File: $ id $
# Version: $ Revision $
Such tags are automatically adapted into corresponding strings after they are submitted to the configuration management server, such as:
# File: $ Id: ussp.py, v 1.22 2004/07/21 04:47:41 hd Exp $
# Version: $ Revision: 1.4 $
---- HD
8 Naming Convention
(Naming Conventions)

The naming conventions for Python libraries are a bit confusing, so we will never make them exactly the same-but there are well-known naming conventions. New modules and packages (including third-party frameworks) must conform to these standards, but for Existing inventory is in different styles, and maintaining internal consistency is preferred.
8.1 Description: Naming Style
(Descriptive: Naming Styles)

There are many different naming styles. The following are helpful in identifying the naming styles in use, independent of their role. The following naming styles are well known:
b (single lowercase letter)
B (single capital letter)
Lowercase string such as: getname
Lowercase strings with underscores such as: _getname
Uppercase string such as: GETNAME
Underlined uppercase string such as: _GETNAME
CapitalizedWords (capitalized word string) (or CapWords, CamelCase-this name is due to its letter appearance.

This is sometimes referred to as StudlyCaps. For example: GetName

mixedCase (mixed case) (different from the first case uppercase string in that the first character is lowercase such as: getName)

Capitalized_Words_With_Underscores (underlined initials) (ugly!)

There is also a style using special prefixes for grouping related names into groups. This is not commonly used in Python,
But to mention it for completeness. For example,
The os.stat () function returns a tuple whose elements traditionally have names like st_mode, st_size, st_mtime, etc. All public functions of the X11 library begin with X.
(In Python, this style is generally considered unnecessary, because property and method names are prefixed with objects, and function names are prefixed with module names.)

In addition, the following special forms with underscores as leading or ending are recognized (these can usually be combined with any custom (use?)):
_single_leading_underscore (leading with an underscore): Weak "internal use" flag.
(For example, "from M import *" will not import objects that begin with an underscore).
single_trailing_underscore_ (ending with an underscore): used to avoid conflicts with Python keywords, for example.
"Tkinter.Toplevel (master, class _ =‘ ClassName ’)".

__double_leading_underscore (double underscore): Class private name since Python 1.4.

__double_leading_and_trailing_underscore__: special (magic) objects or attributes that exist in user-controlled namespaces, such as: __init__, __import__ or __file__. Sometimes they are defined by the user to trigger a specific behavior (magic behavior) (E.g. operator overloading); sometimes inserted by the infrastructure for its own use or for debugging. Therefore, in a future version, the constructor (loosely defined as the Python interpreter and standard library) may intend to build its own A list of magic attributes. User code should generally restrict this convention to its own use. User code that wants to be part of the constructor can use short prefixes in the downline, for example. __Bobo_magic_attr__.

8.2 Description: Naming Convention
(Prescriptive: Naming Conventions)

8.2.1 Names to Avoid
(Names to Avoid)

Never use the character `l’ (lowercase el (the pronunciation, the same below)),
O '(capital letter oh), or I' (capital letter eye) as single-character variable names. In some fonts, these characters cannot be separated from the numbers 1 and 0. When you want to use 'l', use ' L 'instead.

8.2.2 Module name
(Module Names)

Modules should be underlined, short, lowercase names. Because module names are mapped to file names, some file systems are not case sensitive and truncated long names. It is important that the module name is chosen to be fairly short --- This is not a problem on Unix, but it can be a problem when the code is passed to Mac or Windows. When an extension module written in C or C ++ has an accompanying Python module, this Python module provides
For a higher-level (for example, more object-oriented) interface, C / C ++ modules have a leading underscore (eg: _socket)
Python packages should be underlined, short, all lowercase names.
8.2.3 Class Name
(Class Names)

With few exceptions, class names always use the convention of CapWords.

8.2.4 Exception Name
(Exception Names)

If a module defines a single exception for all cases, it is usually called "error" or "Error". It seems that built-in (extended) modules use "error" (eg: os.error), while Python modules usually use "Error" (Example: xdrlib.Error).
The trend seems to be the tendency to use CapWords exception names.

8.2.5 Global variable names
(Global Variable Names)

(Let's hope that these variables are intended to be used only inside the module.) These conventions are similar to those used for functions. They are designed to be used by "from M import *"
Those modules should be underlined before global variables (and internal functions and classes) that you don't want to be imported.
8.2.6 Function Name
(Function Names)

Function names should be lowercase, and underlined words may be used for readability.
mixedCase is only allowed in contexts where this style is already dominant (e.g. threading.py) in order to maintain backward compatibility.

8.2.7 Method names and instance variables
(Method Names and Instance Variables)

This paragraph is roughly the same as a function: lowercase words are usually used, separated by underscores if necessary for readability. A leading underscore is only used for internal methods and instance variables that are not intended as the public interface of the class. Python does not mandate this; It depends on whether the programmer adheres to this convention. Use two leading underscores to indicate class private names. Python concatenates these names with class names:
If the class Foo has a property named __a, it cannot be accessed as Foo .__ a. (An insistent user can still get access through Foo._Foo__a.) In general, double leading underscores should only be used to avoid Name conflicts between attributes in a class (designed for subclassing).

8.2.8 Design of inheritance
(Designing for inheritance)

Always determine if methods and instance variables in a class are to be exposed. In general, never expose data variables unless your implementation is essentially documented. People always prefer to provide a function interface to a class as a replacement (Python Some developers in 2.2 did a pretty good job at this point.) Also, determine whether your properties should be private. The difference between private and non-public is that the former is never used in a derived class, while the latter may Yes. Yes, you should design your class with inheritance in your brain. Private properties must have two leading underscores and no trailing underscores. Non-public properties must have a leading underscore and no trailing underscores. Public attributes There are no leading and trailing underscores, unless they conflict with reserved words. In this case, a single trailing underscore is better than leading or confusing spelling, for example: class_ is better than klass. The last point is somewhat controversial; if compared to class_ You prefer klass, then it's just a matter of consistency.
9 Design recommendations
(Programg Recommendations)

Comparisons with single values like None should always be done with: 'is' or 'is not'. When you mean "if x is not None", be careful about writing "if x"-for example When you test whether a variable or parameter that defaults to None is set to another value. This other value may be a value that is false in a Boolean context!

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

class MessageError (Exception):
    "" "Base class for errors in the email package." ""
Use string methods instead of string modules, unless you must be backwards compatible with versions before Python 2.0. String methods are always very fast and share the same API (application programming interface) as unicode strings

Avoid slicing strings when checking prefixes or suffixes. Use startswith () and endswith () instead, as they are explicit and have fewer errors. For example:

No: if foo [: 3] == ‘bar’:
Yes: if foo.startswith (‘bar‘):
The exception is if your code must work on Python 1.5.2 (but we hope it does not happen!).

Object type comparisons should always use isinstance () instead of direct comparison types. For example:

No: if type (obj) is type (1):
Yes: if isinstance (obj, int):
When checking whether an object is a string, keep in mind that it may also be a unicode string! In Python 2.3, str and unicode have a common base class, basestring, so you can do this:

                if isinstance (obj, basestring):
The StringTypes type is defined for this in the Python 2.2 type module, for example:

from types import StringTypes
if isinstance (obj, StringTypes):
In Python 2.0 and 2.1, you should do this:

from types import StringType, UnicodeType
if isinstance (obj, StringType) or \
   isinstance (obj, UnicodeType):
For sequences, (strings, lists, tuples), the fact that using an empty list is false, so "if not seq" or "if seq" is better than "if len (seq)" or "if not len (seq)" is fine.

Do not rely on meaningful trailing spaces when writing string literals. Such trailing spaces are visually indistinguishable, and some editors (especially recently, reindent.py) will trim them out.

Do not use == to compare boolean values to determine if they are True or False (booleans are new in Pythn 2.3)

No: if greeting == True:
Yes: if greeting:
No: if greeting == True:
Yes: if greeting:
[Turn] Python-coding standards

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.