skip to navigation
skip to content
Title:Style Guide for Python Code
Last-Modified:2012-03-15 08:24:13 +0100 (Thu, 15 Mar 2012)
Author:Guido van Rossum <guido at>, Barry Warsaw <barry at>
翻译:zgia, albert

Introduction 介绍

This document gives coding conventions for the Python code comprising the standard library in the main Python distribution. Please see the companion informational PEP describing style guidelines for the C code in the C implementation of Python [1].

本文档列出的编码约定,是基于主Python发行版标准库的Python代码的。Python的C语言实现的C代码风格指南,请参阅PEP 7[1]

This document was adapted from Guido's original Python Style Guide essay [2], with some additions from Barry's style guide [3]. Where there's conflict, Guido's style rules for the purposes of this PEP. This PEP may still be incomplete (in fact, it may never be finished <wink>).

这篇文档改编自Guido(译者注:Python之父,Guido van Rossum)最初的《Python Style Guide》[2]一文,《Barry's style guide》[3]亦有贡献。对(2文)有冲突的地方,Guido的风格指南更符合这份PEP思想。当然,这份PEP仍不完善(实际上,它可能永远也无法完善<wink>)

A Foolish Consistency is the Hobgoblin of Little Minds 愚蠢的一致性就像没脑子的妖怪

One of Guido's key insights is that code is read much more often than it is written. The guidelines provided here are intended to improve the readability of code and make it consistent across the wide spectrum of Python code. As PEP 20 says, "Readability counts".

Guido的关键见解之一是阅读代码比怎么写代码更重要。这份指南意图提高代码的可阅读性,使整个 Python 代码的代码保持一致。正如 PEP 20 所表述的,“可读性很重要”。(译者注:可以点击这里查看由lanphaday翻译的“The Zen of Python”。)

A style guide is about consistency. Consistency with this style guide is important. Consistency within a project is more important. Consistency within one module or function is most important.


But most importantly: know when to be inconsistent -- sometimes the style guide just doesn't apply. When in doubt, use your best judgment. Look at other examples and decide what looks best. And don't hesitate to ask!


Two good reasons to break a particular rule:


  1. When applying the rule would make the code less readable, even for someone who is used to reading code that follows the rules.


  2. To be consistent with surrounding code that also breaks it (maybe for historic reasons) -- although this is also an opportunity to clean up someone else's mess (in true XP style).

    欲与周围的代码的代码保持一致,也会打破这个规则(也许是历史的原因)————虽然这也是一个机会来收拾别人的烂摊子(真正的XP风格)。(译者注:XP,Xtreme Programming,极限编程)

Code lay-out 代码布局

Indentation 缩进

Use 4 spaces per indentation level.

每级缩进使用 4 个空格。

For really old code that you don't want to mess up, you can continue to use 8-space tabs.


Continuation lines should align wrapped elements either vertically using Python's implicit line joining inside parentheses, brackets and braces, or using a hanging indent. When using a hanging indent the following considerations should be applied; there should be no arguments on the first line and further indentation should be used to clearly distinguish itself as a continuation line.



# Aligned with opening delimiter
# 与开始的分隔符对齐
foo = long_function_name(var_one, var_two,
                         var_three, var_four)

# More indentation included to distinguish this from the rest.
# 更多的缩进,更加的清晰
def long_function_name(
        var_one, var_two, var_three,


# Arguments on first line forbidden when not using vertical alignment
# 没有使用垂直对齐时,禁止把参数放在第一行
foo = long_function_name(var_one, var_two,
    var_three, var_four)

# Further indentation required as indentation is not distinguishable
# 缩进不够,代码不清晰
def long_function_name(
    var_one, var_two, var_three,



# Extra indentation is not necessary.
foo = long_function_name(
  var_one, var_two,
  var_three, var_four)

Tabs or Spaces? 制表符或者空格?

Never mix tabs and spaces.


The most popular way of indenting Python is with spaces only. The second-most popular way is with tabs only. Code indented with a mixture of tabs and spaces should be converted to using spaces exclusively. When invoking the Python command line interpreter with the -t option, it issues warnings about code that illegally mixes tabs and spaces. When using -tt these warnings become errors. These options are highly recommended!

最流行的 Python 缩进方式是仅使用空格,其次是仅使用制表符。混合着制表符和空格缩进的代码将被转换成仅使用空格。使用带-t选项来调用Python命令行解释器时,代码中非法混用制表符和空格会给出警告。当使用-tt选项时这些警告就会变成错误。高度建议使用这些选项。

For new projects, spaces-only are strongly recommended over tabs. Most editors have features that make this easy to do.


Maximum Line Length 行的最大长度

Limit all lines to a maximum of 79 characters.

限制所有行的最大长度为 79 个字符。

There are still many devices around that are limited to 80 character lines; plus, limiting windows to 80 characters makes it possible to have several windows side-by-side. The default wrapping on such devices disrupts the visual structure of the code, making it more difficult to understand. Therefore, please limit all lines to a maximum of 79 characters. For flowing long blocks of text (docstrings or comments), limiting the length to 72 characters is recommended.

周围还有很多设备限制每行 80个字符。而且,限制窗口显示 80 个字符可以并排显示多个窗口。有些设备上,默认折行会打乱代码结构,不易理解。因此,请限制所有行的最大长度为 79 个字符。对一大段长文本(文档字符串或注释),推荐限制每行最多72个字符。

The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces. Long lines can be broken over multiple lines by wrapping expressions in parentheses. These should be used in preference to using a backslash for line continuation. Make sure to indent the continued line appropriately. The preferred place to break around a binary operator is after the operator, not before it. 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 don't think so -- values are %s, %s" %
                             (width, height))
        Blob.__init__(self, width, height,
                      color, emphasis, highlight)

Blank Lines 空行

Separate top-level function and class definitions with two blank lines.


Method definitions inside a class are separated by a single blank line.


Extra blank lines may be used (sparingly) to separate groups of related functions. Blank lines may be omitted between a bunch of related one-liners (e.g. a set of dummy implementations).

(谨慎地)使用额外的空白行来分隔一组相关的函数。一堆相关的单行代码之间的空白行可以省略(例如,一组dummy implementations)。

Use blank lines in functions, sparingly, to indicate logical sections.


Python accepts the control-L (i.e. ^L) form feed character as whitespace; Many tools treat these characters as page separators, so you may use them to separate pages of related sections of your file. Note, some editors and web-based code viewers may not recognize control-L as a form feed and will show another glyph in its place.


Encodings (PEP 263) 编码

Code in the core Python distribution should always use the ASCII or Latin-1 encoding (a.k.a. ISO-8859-1). For Python 3.0 and beyond, UTF-8 is preferred over Latin-1, see PEP 3120.

Python核心发行代码应该总是使用 ASCII 或 Latin-1 编码 (又名 ISO-8859-1)。Python 3.0 和以后的版本,首选 UTF-8 而不是 Latin-1,请查看 PEP 3120 获取更多信息。(译者注:对中文项目,请首选UTF-8。)

ASCII 编码的文件不应该有coding cookie(译者注:# -*- coding: utf-8 -*-,# coding=utf-8)。Latin-1(或 UTF-8 )只应该当注释或文档字符串涉及作者名需要 Latin-1 时才使用;否则,使用 \x\u\U等转义字符是在字符串中包含非 ASCII 数据的首选方法。

For Python 3.0 and beyond, the following policy is prescribed for the standard library (see PEP 3131): All identifiers in the Python standard library MUST use ASCII-only identifiers, and SHOULD use English words wherever feasible (in many cases, abbreviations and technical terms are used which aren't English). In addition, string literals and comments must also be in ASCII. The only exceptions are (a) test cases testing the non-ASCII features, and (b) names of authors. Authors whose names are not based on the latin alphabet MUST provide a latin transliteration of their names.

对Python 3.0 和以后的版本来说,下述政策仅对标准库作出限制(请查阅PEP 3131):All identifiers in the Python standard library MUST use ASCII-only identifiers, and SHOULD use English words wherever feasible (in many cases, abbreviations and technical terms are used which aren't English). In addition, string literals and comments must also be in ASCII. The only exceptions are (a) test cases testing the non-ASCII features, and (b) names of authors. Authors whose names are not based on the latin alphabet MUST provide a latin transliteration of their names.

Open source projects with a global audience are encouraged to adopt a similar policy.


Imports 导入

  • Imports should usually be on separate lines, e.g.:


    Yes: import os
         import sys
    No:  import sys, os

    It's okay to say this though:


    from subprocess import Popen, PIPE
  • Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants.


    Imports should be grouped in the following order:


    1. standard library imports 标准库导入
    2. related third party imports 相关第三方导入
    3. local application/library specific imports 本地应用程序/库的特定导入

    You should put a blank line between each group of imports.


    Put any relevant __all__ specification after the imports.

    在导入之后放置任何相关的 __all__ 说明书。

  • Relative imports for intra-package imports are highly discouraged. Always use the absolute package path for all imports. Even now that PEP 328 is fully implemented in Python 2.5, its style of explicit relative imports is actively discouraged; absolute imports are more portable and usually more readable.

    非常不推荐在包内导入中使用相对路径导入。对所有导入来说,总是使用绝对包路径导入。尽管PEP 328 在Python 2.5中已经完全实现,但是相对路径导入一直以来都是不推荐的,绝对路径导入更容易移植,而且常常更容易阅读。

  • When importing a class from a class-containing module, it's usually okay to spell this:


    from myclass import MyClass
    from import YourClass

    If this spelling causes local name clashes, then spell them


    import myclass

    and use "myclass.MyClass" and "".

    分别这样使用:"myclass.MyClass" 和 ""。

Whitespace in Expressions and Statements 表达式和语句中的空格

Pet Peeves 宠物的烦恼(即无伤大雅的小问题)

Avoid extraneous whitespace in the following situations:


  • Immediately inside parentheses, brackets or braces.


    Yes: spam(ham[1], {eggs: 2})
    No:  spam( ham[ 1 ], { eggs: 2 } )
  • Immediately before a 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
  • Immediately before the open parenthesis that starts the argument list of a function call:


    Yes: spam(1)
    No:  spam (1)
  • Immediately before the open parenthesis that starts an indexing or slicing:


    Yes: dict['key'] = list[index]
    No:  dict ['key'] = list [index]
  • More than one space around an assignment (or other) operator to align it with another.



    x = 1
    y = 2
    long_variable = 3


    x             = 1
    y             = 2
    long_variable = 3

Other Recommendations 其他建议

  • Always surround these binary operators with a single space on either side: assignment (=), augmented assignment (+=, -= etc.), comparisons (==, <, >, !=, <>, <=, >=, in, not in, is, is not), Booleans (and, or, not).

    总是在这些二元运算符前后加一个空格:赋值(=),自增赋值(+=-= 等等), 比较(==<>!=<><=>=innot inisis not),布尔运算(andornot)。

  • Use spaces around arithmetic operators:



    i = i + 1
    submitted += 1
    x = x * 2 - 1
    hypot2 = x * x + y * y
    c = (a + b) * (a - b)


    submitted +=1
    x = x*2 - 1
    hypot2 = x*x + y*y
    c = (a+b) * (a-b)
  • Don't use spaces around the = sign when used to indicate a keyword argument or a default parameter value.

    不要在一个关键字参数或者一个缺省参数值的 = 符号前后加一个空格。


    def complex(real, imag=0.0):
        return magic(r=real, i=imag)


    def complex(real, imag = 0.0):
        return magic(r = real, i = imag)
  • Compound statements (multiple statements on the same line) are generally discouraged.



    if foo == 'blah':

    Rather not:

    if foo == 'blah': do_blah_thing()
    do_one(); do_two(); do_three()
  • While sometimes it's okay to put an if/for/while with a small body on the same line, never do this for multi-clause statements. Also avoid folding such long lines!


    Rather not:

    if foo == 'blah': do_blah_thing()
    for x in lst: total += x
    while t < 10: t = delay()

    Definitely not:


    if foo == 'blah': do_blah_thing()
    else: do_non_blah_thing()
    try: something()
    finally: cleanup()
    do_one(); do_two(); do_three(long, argument,
                                 list, like, this)
    if foo == 'blah': one(); two(); three()

Comments 注释

Comments that contradict the code are worse than no comments. Always make a priority of keeping the comments up-to-date when the code changes!


Comments should be complete sentences. If a comment is a phrase or sentence, its first word should be capitalized, unless it is an identifier that begins with a lower case letter (never alter the case of identifiers!).


If a comment is short, the period at the end can be omitted. Block comments generally consist of one or more paragraphs built out of complete sentences, and each sentence should end in a period.

如果注释很短,那么结尾的句号可以省略。块注释通常由一个或多个段落组成, 这些段落由完整的句子构成,每个句子都应该使用句号结尾。

You should use two spaces after a sentence-ending period.


When writing English, Strunk and White apply.

Python coders from non-English speaking countries: please write your comments in English, unless you are 120% sure that the code will never be read by people who don't speak your language.

来自非英语国家的Python程序员:请使用英语写注释,除非你120%肯定你的代码将永远不会 被不说你的语言的人阅读。

Block Comments 块注释

Block comments generally apply to some (or all) code that follows them, and are indented to the same level as that code. Each line of a block comment starts with a # and a single space (unless it is indented text inside the comment).

块注释在一些(或全部)代码之前,并和代码缩进一致。每行注释均以 # 开头,然后紧跟一个空格(除非在注释内缩进)。

Paragraphs inside a block comment are separated by a line containing a single #.

块注释内的段落使用仅含 # 的单行分隔。

Inline Comments 行内注释

Use inline comments sparingly.


An inline comment is a comment on the same line as a statement. Inline comments should be separated by at least two spaces from the statement. They should start with a # and a single space.

内嵌注释是一种和语句在同一行的注释。内嵌注释至少和语句间隔2个空格。他们开始于一个 # 和一个空格。

Inline comments are unnecessary and in fact distracting if they state the obvious. Don't do this:


x = x + 1                 # Increment x

But sometimes, this is useful:


x = x + 1                 # Compensate for border

Documentation Strings 文档字符串

Conventions for writing good documentation strings (a.k.a. "docstrings") are immortalized in PEP 257.

编写良好的文档字符串(documentation strings,又名 "docstrings")的约定永生(:()在 PEP 257

  • Write docstrings for all public modules, functions, classes, and methods. Docstrings are not necessary for non-public methods, but you should have a comment that describes what the method does. This comment should appear after the def line.

    所有的公告模块,函数,类和方法都需要编写文档字符串。对非公共的方法而言,文档字符串则不是必要的,但是可以使用一个注释来描述这个方法。这个注释必须位于 def 行之后。

  • PEP 257 describes good docstring conventions. Note that most importantly, the """ that ends a multiline docstring should be on a line by itself, and preferably preceded by a blank line, e.g.:

    PEP 257 描述了一个良好的文档字符串的编写约定。注意最重要的是,""" 作为多行的文档字符串的结束,应该单独一行,并且之前有一个空行,例如:

    """Return a foobang
    Optional plotz says to frobnicate the bizbaz first.
  • For one liner docstrings, it's okay to keep the closing """ on the same line.

    对单行的文档字符串来说,结尾的 """ 在同一行。

Version Bookkeeping 版本注记

If you have to have Subversion, CVS, or RCS crud in your source file, do it as follows.


__version__ = "$Revision: dc5a21b8bc47 $"
# $Source$

These lines should be included after the module's docstring, before any other code, separated by a blank line above and below.


Naming Conventions 命名约定

The naming conventions of Python's library are a bit of a mess, so we'll never get this completely consistent -- nevertheless, here are the currently recommended naming standards. New modules and packages (including third party frameworks) should be written to these standards, but where an existing library has a different style, internal consistency is preferred.

Python库的命名约定有点乱,所以我们从未达成完全一致。但是,目前有一些推荐的标准。 新的模块和包(包括第三方框架)应该用这些标准,但是拥有不同风格的固有库,还是保持内部统一更好。

Descriptive: Naming Styles 描述:命名风格

There are a lot of different naming styles. It helps to be able to recognize what naming style is being used, independently from what they are used for.


The following naming styles are commonly distinguished:


  • b (single lowercase letter) (单个小写字母)

  • B (single uppercase letter) (单个大写字母)

  • lowercase 小写字母

  • lower_case_with_underscores 使用下划线分隔的小写字母

  • UPPERCASE 大写字母


  • CapitalizedWords (or CapWords, or CamelCase -- so named because of the bumpy look of its letters [4]). This is also sometimes known as StudlyCaps.

    CapitalizedWords (或 CapWords,或 CamelCase -- 这样命名因为其字母有起伏的外观[4])。这有时也被称为 StudlyCaps。

    Note: When using abbreviations in CapWords, capitalize all the letters of the abbreviation. Thus HTTPServerError is better than HttpServerError.


  • mixedCase (differs from CapitalizedWords by initial lowercase character!)


  • Capitalized_Words_With_Underscores (ugly!)(丑陋之极!)

There's also the style of using a short unique prefix to group related names together. This is not used much in Python, but it is mentioned for completeness. For example, the os.stat() function returns a tuple whose items traditionally have names like st_mode, st_size, st_mtime and so on. (This is done to emphasize the correspondence with the fields of the POSIX system call struct, which helps programmers familiar with that.)

也有用唯一短前缀来组织相关字符的方法。在Python中用的不多。但为了完整提一下。比如,os.stat()返回一个元组, 里面的条目是传统的名字,如st_mode, st_size, st_mtime 等。 (这么做是为了与 POSIX 系统的调用一致,以帮助程序员熟悉它。)

The X11 library uses a leading X for all its public functions. In Python, this style is generally deemed unnecessary because attribute and method names are prefixed with an object, and function names are prefixed with a module name.


In addition, the following special forms using leading or trailing underscores are recognized (these can generally be combined with any case convention):


  • _single_leading_underscore: weak "internal use" indicator. E.g. from M import * does not import objects whose name starts with an underscore.

    _single_leading_underscore:(单下划线开始)弱"内部使用"指示器。例如:from M import * 不会导入以下划线开始的对象。

  • single_trailing_underscore_: used by convention to avoid conflicts with Python keyword, e.g.


    Tkinter.Toplevel(master, class_='ClassName')
  • __double_leading_underscore: when naming a class attribute, invokes name mangling (inside class FooBar, __boo becomes _FooBar__boo; see below).

    __double_leading_underscore:(双下划线开始)命名一个类的属性时,调用"名字变化"(类FooBar中,__boo 变为了 _FooBar__boo; 见下文)。

  • __double_leading_and_trailing_underscore__: "magic" objects or attributes that live in user-controlled namespaces. E.g. __init__, __import__ or __file__. Never invent such names; only use them as documented.

    __double_leading_and_trailing_underscore__:(双下划线开始和结束)"magic"对象或属性存活于用户控制的命名空间。 例如__init__, __import____file__。永远不要起这样的名字;只在文档中使用。

Prescriptive: Naming Conventions 说明:命名规范

Names to Avoid 避免使用的名字

Never use the characters 'l' (lowercase letter el), 'O' (uppercase letter oh), or 'I' (uppercase letter eye) as single character variable names.

永远不要使用 'l'(小写的L),'O'(大写的O),或者'I'(大写的I)作为单字变量名。

In some fonts, these characters are indistinguishable from the numerals one and zero. When tempted to use 'l', use 'L' instead.

在某些字体中,这些字很难和数字的0 和 1 区分。当打算用'l'的时候,用'L'来代替。

Package and Module Names 包和模块名称

Modules should have short, all-lowercase names. Underscores can be used in the module name if it improves readability. Python packages should also have short, all-lowercase names, although the use of underscores is discouraged.

模块应该用简短的,全小写的名字。如果能增强可读性的话,可以使用下划线。 Python的包也要用全小写的,短名称,但是不建议用下划线。

Since module names are mapped to file names, and some file systems are case insensitive and truncate long names, it is important that module names be chosen to be fairly short -- this won't be a problem on Unix, but it may be a problem when the code is transported to older Mac or Windows versions, or DOS.

因为模块名称和文件名关联,而且某些文件系统大小写不敏感,也会截断过长的名字。所以模块选用相当简短的名字是很重要的。 在Unix下不会有这样的问题,但是在早些的Mac、Windows 或者 DOS下会有这样的问题。

When an extension module written in C or C++ has an accompanying Python module that provides a higher level (e.g. more object oriented) interface, the C/C++ module has a leading underscore (e.g. _socket).

当用C或C++连编写一个含有Python模块提供更高层(比如,更加面向对象)接口的扩展模块时,这个C/C++模块要有一个前导下划线(例如 _socket)。

Class Names 类名

Almost without exception, class names use the CapWords convention. Classes for internal use have a leading underscore in addition.


Exception Names 异常名

Because exceptions should be classes, the class naming convention applies here. However, you should use the suffix "Error" on your exception names (if the exception actually is an error).

异常也是类,所以这里也用类名规则。但是,你异常名应该用前缀 "Error"(如果你的异常确实是个错误的话)。

Global Variable Names 全局变量名

(Let's hope that these variables are meant for use inside one module only.) The conventions are about the same as those for functions.


Modules that are designed for use via from M import * should use the __all__ mechanism to prevent exporting globals, or use the older convention of prefixing such globals with an underscore (which you might want to do to indicate these globals are "module non-public").

被设计为通过from M import *导入的模块。应该用__all__机制来防止导出全局。 或者使用过去的全局变量前置下划线的规则(这是为了说明这些变量是"模块私有的")。

Function Names 函数名

Function names should be lowercase, with words separated by underscores as necessary to improve readability.


mixedCase is allowed only in contexts where that's already the prevailing style (e.g., to retain backwards compatibility.


Function and method arguments 函数和方法参数

Always use self for the first argument to instance methods.


Always use cls for the first argument to class methods.


If a function argument's name clashes with a reserved keyword, it is generally better to append a single trailing underscore rather than use an abbreviation or spelling corruption. Thus class_ is better than clss. (Perhaps better is to avoid such clashes by using a synonym.)

如果函数的参数名和保留字冲突。用结尾下划线比缩写或是滥用的组词更好。因此 class_clss好。(也许,更好的避免冲突的方式是用同义词。)

Method Names and Instance Variables 方法名和实例变量

Use the function naming rules: lowercase with words separated by underscores as necessary to improve readability.


Use one leading underscore only for non-public methods and instance variables.


To avoid name clashes with subclasses, use two leading underscores to invoke Python's name mangling rules.


Python mangles these names with the class name: if class Foo has an attribute named __a, it cannot be accessed by Foo.__a. (An insistent user could still gain access by calling Foo._Foo__a.) Generally, double leading underscores should be used only to avoid name conflicts with attributes in classes designed to be subclassed.

Python 用类名来变化这个名字:如果类Foo有个属性叫做__a,那么它不能用 Foo.__a读取。 (执着的用户还是可以用Foo._Foo__a.读取。)

Note: there is some controversy about the use of __names (see below).


Constants 常量

Constants are usually defined on a module level and written in all capital letters with underscores separating words. Examples include MAX_OVERFLOW and TOTAL.


Designing for inheritance 继承设计

Always decide whether a class's methods and instance variables (collectively: "attributes") should be public or non-public. If in doubt, choose non-public; it's easier to make it public later than to make a public attribute non-public.

总要考虑一个类的方法或实例变量(总体而言:属性)应该是公用的或者非公用的。如果不能确定的话,设计为私有的。 因为,之后将一个私有的改为公有的要比将公有的变为私有的容易。

Public attributes are those that you expect unrelated clients of your class to use, with your commitment to avoid backward incompatible changes. Non-public attributes are those that are not intended to be used by third parties; you make no guarantees that non-public attributes won't change or even be removed.

公有属性,是你希望与这个类无关的客户使用的,并通过你的委托机制来避免由于属性变更导致的向后不兼容。 私有属性,是你不希望被第三方使用的。你不能保证私有属性不会改变甚至被删除。

We don't use the term "private" here, since no attribute is really private in Python (without a generally unnecessary amount of work).


Another category of attributes are those that are part of the "subclass API" (often called "protected" in other languages). Some classes are designed to be inherited from, either to extend or modify aspects of the class's behavior. When designing such a class, take care to make explicit decisions about which attributes are public, which are part of the subclass API, and which are truly only to be used by your base class.

另一种属性,是"subclass API" 的一部分(通常,在某些语言里被称作"protected")。有一些类设计的时候是用来继承的。 用于扩展或者改变类的自身行为的某些方面。当设计这样的类的时候,一定要弄清楚哪些属性是公有的,哪些是subclass API的子集,哪些是真正只在自己的基类中使用的

With this in mind, here are the Pythonic guidelines:


  • Public attributes should have no leading underscores.


  • If your public attribute name collides with a reserved keyword, append a single trailing underscore to your attribute name. This is preferable to an abbreviation or corrupted spelling. (However, notwithstanding this rule, 'cls' is the preferred spelling for any variable or argument which is known to be a class, especially the first argument to a class method.)

    如果你的公有属性和保留字冲突。那么在属性名后面加一个下划线。这要比缩写和糟糕的拼写好很多。 (然而,尽管有这样的规则,'cls'在用作变量,或者参数时,是代表'类'的最佳选择。特别是用作类方法的第一个参数)

    Note 1: See the argument name recommendation above for class methods.


  • For simple public data attributes, it is best to expose just the attribute name, without complicated accessor/mutator methods. Keep in mind that Python provides an easy path to future enhancement, should you find that a simple data attribute needs to grow functional behavior. In that case, use properties to hide functional implementation behind simple data attribute access syntax.

    对于单一的公有数据属性,最好是直接用其属性名,而非复杂的存取器/突变期方法。 需要记得的是,Python为今后由简单的数据属性扩充为方法操作提供了简单的途径。 因此,运用属性来实现简单数据存取语法对于方法实现的透明化处理。

    Note 1: Properties only work on new-style classes.

    注意1:属性只在new-style 类中起作用

    Note 2: Try to keep the functional behavior side-effect free, although side-effects such as caching are generally fine.


    Note 3: Avoid using properties for computationally expensive operations; the attribute notation makes the caller believe that access is (relatively) cheap.


  • If your class is intended to be subclassed, and you have attributes that you do not want subclasses to use, consider naming them with double leading underscores and no trailing underscores. This invokes Python's name mangling algorithm, where the name of the class is mangled into the attribute name. This helps avoid attribute name collisions should subclasses inadvertently contain attributes with the same name.

    如果你的类打算用来继承的话,并且你的属性不希望子类继承,那么考虑用双下划线开头,不要有结尾下划线。这样会调用 Python的"名称变化术"算法,它会把类的名字错位成属性名。这样可以帮助我们避免在子类中不小心包含了相同的名字造成的冲突。

    Note 1: Note that only the simple class name is used in the mangled name, so if a subclass chooses both the same class name and attribute name, you can still get name collisions.

    注意1:要注意的是只有简单类名(simple class name)才能在名称错位中使用。 所以,如果一个子类同时用相同的类名和属性名,还是会造成名称冲突。

    Note 2: Name mangling can make certain uses, such as debugging and __getattr__(), less convenient. However the name mangling algorithm is well documented and easy to perform manually.

    "名称变化术"可用作某些用途,比如调试,__getattr__(),不太方便。 但是"名称变化术"有详实的文档,而且容易操作。

    Note 3: Not everyone likes name mangling. Try to balance the need to avoid accidental name clashes with potential use by advanced callers.


Programming Recommendations  程序设计建议

  • Code should be written in a way that does not disadvantage other implementations of Python (PyPy, Jython, IronPython, Cython, Psyco, and such).

    代码应该用不损害其他Python实现的方式去编写(PyPy, Jython, IronPython, Cython, Psyco 等)

    For example, do not rely on CPython's efficient implementation of in-place string concatenation for statements in the form a += b or a = a + b. Those statements run more slowly in Jython. In performance sensitive parts of the library, the ''.join() form should be used instead. This will ensure that concatenation occurs in linear time across various implementations.

    例如,不要依赖于CPython的高效内置字符连接语句a += b or a = a + b.这些语句在Jython中运行较慢。在性能敏感的库中,应该用''.join() 来取代。这样可以保证在不同的实现中,字符链接花费的时间都呈线性。

  • Comparisons to singletons like None should always be done with is or is not, never the equality operators.

    Also, beware of writing if x when you really mean if x is not None -- e.g. when testing whether a variable or argument that defaults to None was set to some other value. The other value might have a type (such as a container) that could be false in a boolean context!

    与诸如None这样的字符比较时,要使用is or is not,永远不要用等于操作。

    同样地,在测试一个变量或参数默认值为None被设置为其他值时(比如if x表示if x is not None时),要注意。 这个值应该有一个能在布尔逻辑的上下文中为false的类型(比如容器)。

  • When implementing ordering operations with rich comparisons, it is best to implement all six operations (__eq__, __ne__, __lt__, __le__, __gt__, __ge__) rather than relying on other code to only exercise a particular comparison.

    当用复杂比较实现排序操作时,最好去实现全部六个操作(__eq__, __ne__, __lt__, __le__, __gt__, __ge__),而不是依靠其他的代码去实现一些怪异的比较。

    To minimize the effort involved, the functools.total_ordering() decorator provides a tool to generate missing comparison methods.


    PEP 207 indicates that reflexivity rules are assumed by Python. Thus, the interpreter may swap y > x with x < y, y >= x with x <= y, and may swap the arguments of x == y and x != y. The sort() and min() operations are guaranteed to use the < operator and the max() function uses the > operator. However, it is best to implement all six operations so that confusion doesn't arise in other contexts.

    PEP 207指出Python实现了反射。因此,解释器会将y > x 转换为 x < y, y >= x转换为 x <= y,也会转换x == yx != y的参数.The sort()min()被确保使用<操作符,max()使用>操作符。 但是,最好实现全部六个操作,以避免在其他地方造成的冲突。

  • Use class-based exceptions.


    String exceptions in new code are forbidden, because this language feature is being removed in Python 2.6.


    Modules or packages should define their own domain-specific base exception class, which should be subclassed from the built-in Exception class. Always include a class docstring. E.g.:


    class MessageError(Exception):
        """Base class for errors in the email package."""

    Class naming conventions apply here, although you should add the suffix "Error" to your exception classes, if the exception is an error. Non-error exceptions need no special suffix.

    在这里用到类命名规范。尽管当你的“异常”是一个“错误”(error)时,你应该在自己的异常类加上后缀"Error"。 非错误类(Non-error)异常,不需要特别的后缀。

  • When raising an exception, use raise ValueError('message') instead of the older form raise ValueError, 'message'.

    当抛出一个异常的时候,使用raise ValueError('message')代替旧的raise ValueError, 'message'格式。

    The paren-using form is preferred because when the exception arguments are long or include string formatting, you don't need to use line continuation characters thanks to the containing parentheses. The older form will be removed in Python 3.

    推荐使用这种括弧的格式,当异常的参数很长或者是格式化字符串的时候,由于括号的关系,我们不需要使用连字符。 旧的格式在Python 3 中被移除。

  • When catching exceptions, mention specific exceptions whenever possible instead of using a bare except: clause.

    当捕获一个异常的时候,要用详细异常声明代替光秃秃的except: 语句.

    For example, use:

        import platform_specific_module
    except ImportError:
        platform_specific_module = None

    A bare except: clause will catch SystemExit and KeyboardInterrupt exceptions, making it harder to interrupt a program with Control-C, and can disguise other problems. If you want to catch all exceptions that signal program errors, use except Exception: (bare except is equivalent to except BaseException:).

    一个空的except:语句将会捕获 SystemExit 和 KeyboardInterrrupt 异常。这会使得很难用Control-C来中断一个程序,并且还会隐藏其他的问题。 如果你想捕获一个程序中的所有异常,使用except Exception: (bare 和except BaseException:是等价的)。

    A good rule of thumb is to limit use of bare 'except' clauses to two cases:


    1. If the exception handler will be printing out or logging the traceback; at least the user will be aware that an error has occurred.


    2. If the code needs to do some cleanup work, but then lets the exception propagate upwards with raise. try...finally can be a better way to handle this case.

      如果代码要做一些收尾工作,但是随后要用 raise向上抛出异常。try...finally可以更好地处理这个问题。

  • Additionally, for all try/except clauses, limit the try clause to the absolute minimum amount of code necessary. Again, this avoids masking bugs.

    另外,对于所有的try/except语句,限制try语句来减少必要代码的数量。 再者,可以避免掩盖问题。


        value = collection[key]
    except KeyError:
        return key_not_found(key)
        return handle_value(value)


        # Too broad!
        return handle_value(collection[key])
    except KeyError:
        # Will also catch KeyError raised by handle_value()
        return key_not_found(key)
  • Use string methods instead of the string module.


    String methods are always much faster and share the same API with unicode strings. Override this rule if backward compatibility with Pythons older than 2.0 is required.


  • Use ''.startswith() and ''.endswith() instead of string slicing to check for prefixes or suffixes.


    startswith() and endswith() are cleaner and less error prone. For example:

    startswith() and endswith() 更加绿色,错误更少。例如:

    Yes: if foo.startswith('bar'):
    No:  if foo[:3] == 'bar':

    The exception is if your code must work with Python 1.5.2 (but let's hope not!).

    例外的就是如果你的代码必须在Python 1.5.2运行(但是,假设它不是)。

  • Object type comparisons should always use isinstance() instead of comparing types directly.

    对象类型比较总要用 isinstance() 而非直接比较

    Yes: if isinstance(obj, int):
    No:  if type(obj) is type(1):

    When checking if an object is a string, keep in mind that it might be a unicode string too! In Python 2.3, str and unicode have a common base class, basestring, so you can do:

    当检测一个对象是否是字符串是,记住,它可能是unicode字符。在Python 2.3, str和unicode有同样的基类——basestring, 那么你可以这样做:

    if isinstance(obj, basestring):
  • For sequences, (strings, lists, tuples), use the fact that empty sequences are false.

    对于序列,(strings, lists, tuples),利用空序列为false这一点。

    Yes: if not seq:
         if seq:
    No: if len(seq)
        if not len(seq)
  • Don't write string literals that rely on significant trailing whitespace. Such trailing whitespace is visually indistinguishable and some editors (or more recently, will trim them.


  • Don't compare boolean values to True or False using ==.

    别用‘==’进行布尔值和 True 或者 False 的比较

    Yes:   if greeting:
    No:    if greeting == True:
    Worse: if greeting is True: