# 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].

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>).

This style guide evolves over time as additional conventions are identified and past conventions are rendered obsolete by changes in the language itself.

Many projects have their own coding style guidelines. In the event of any conflicts, such project-specific guides take precedence for that project.

# 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，极限编程）

3. Because the code in question predates the introduction of the guideline and there is no other reason to be modifying that code.                                                                                                                             因为在引入PEP8规范前已写好的代码，没有理由去修改这部分代码

4. When the code needs to remain compatible with older versions of Python that don't support the feature recommended by the style guide                                                                                                                                                             当代码需要与不支持EP8规范的旧版本Python兼容时

# Code lay-out 代码布局

## Indentation 缩进和换行

Use 4 spaces per indentation level.

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.

Yes:

# 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,
var_four):
print(var_one)


No:

# 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,
var_four):
print(var_one)


Optional:

#
Hanging indents *may* be indented to other than 4 spaces.
foo = long_function_name(
var_one, var_two,
var_three, var_four)

When the conditional part of an if-statement is long enough to require that it be written across multiple lines, it's worth noting that the combination of a two character keyword (i.e. if), plus a single space, plus an opening parenthesis creates a natural 4-space indent for the subsequent lines of the multiline conditional. This can produce a visual conflict with the indented suite of code nested inside the if-statement, which would also naturally be indented to 4 spaces. This PEP takes no explicit position on how (or whether) to further visually distinguish such conditional lines from the nested suite inside the if-statement. Acceptable options in this situation include, but are not limited to:

# No extra indentation.没有额外的缩进
if (this_is_one_thing and
that_is_another_thing):
do_something()

# Add a comment, which will provide some distinction in editors 添加注释将条件行与嵌套代码做区别
if (this_is_one_thing and
that_is_another_thing):
# Since both conditions are true, we can frobnicate.
do_something()

# Add some extra indentation on the conditional continuation line.在条件连续行上添加一些额外的缩进
if (this_is_one_thing
and that_is_another_thing):
do_something()


(Also see the discussion of whether to break before or after binary operators below.)

The closing brace/bracket/parenthesis on multiline constructs may either line up under the first non-whitespace character of the last line of list, as in:

my_list = [
1, 2, 3,
4, 5, 6,
]
result = some_function_that_takes_arguments(
'a', 'b', 'c',
'd', 'e', 'f',
)


or it may be lined up under the first character of the line that starts the multiline construct, as in:

my_list = [
1, 2, 3,
4, 5, 6,
]
result = some_function_that_takes_arguments(
'a', 'b', 'c',
'd', 'e', 'f',
)

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

Spaces are the preferred indentation method.

Tabs should be used solely to remain consistent with code that is already indented with tabs.

Python 3 disallows mixing the use of tabs and spaces for indentation.

Python 2 code indented with a mixture of tabs and spaces should be converted to using spaces exclusively.

When invoking the Python 2 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!

## Maximum Line Length 行的最大长度

Limit all lines to a maximum of 79 characters.

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.

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.

Python接受control-L（即^L）换页符作为空格；许多工具把这些字符当作页面分隔符，所以你可以在文件中使用它们来分隔相关段落。请注意，一些编辑器和基于Web的代码阅读器可能无法识别control-L为换页，将在其位置显示另一个字形。

## 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.

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 foo.bar.yourclass import YourClass


If this spelling causes local name clashes, then spell them

如果上述写法导致内部名称冲突，那么可以这么写：

import myclass
import foo.bar.yourclass


and use "myclass.MyClass" and "foo.bar.yourclass.YourClass".

分别这样使用："myclass.MyClass" 和 "foo.bar.yourclass.YourClass"。

# 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.

在赋值（或其他）语句的运算符周围，不要为了对齐而使用多个空格。

Yes:

x = 1
y = 2
long_variable = 3


No:

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 (==<>!=<><=>=innot inisis not), Booleans (andornot).

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

• Use spaces around arithmetic operators:

在算术运算符前后加空格：

Yes:

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


No:

i=i+1
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.

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

Yes:

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


No:

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

• Compound statements (multiple statements on the same line) are generally discouraged.

通常不推荐使用复合语句（一行代码中有多条语句）。

Yes:

if foo == 'blah':
do_blah_thing()
do_one()
do_two()
do_three()


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!

通常情况下，一行代码包括一个小的if/for/while块，是可以的。但是多子句绝不可以。同样，需要避免折叠类似的长代码行！

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 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.

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 #.

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.

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.

• 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 大写字母

• UPPER_CASE_WITH_UNDERSCORES 使用下划线分隔的大写字母

• 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.

注意：当首字大写中用到缩写时，所有字符用大写。因此HTTPSeverError比HttpSeverError好。

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

mixedCase（不同于首字符大写，开始是小写字母！）

• 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_modest_sizest_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.)

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.

X11库的所有公共函数用了前导X。在Python中，这种风格通常被视为非必须的，因为属性和方法的名字用类做前缀，方法名用模块名做前缀。

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_trailing_underscore_: used by convention to avoid conflicts with Python keyword, e.g.

single_trailing_underscore_：（单下划线结束）规定使用其来避免与Python关键字冲突，例如：

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_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.

## 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.

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

### 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.

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.

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).

### 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).

### 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").

### 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. threading.py), 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.)

### 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.

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.

注意1：参看之前的类方法参数命名建议

• 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.

注意3:并不是所有人喜欢"名称变化术"。尝试平衡需求，避免由于之前潜在的调用造成的意外的名称冲突。

# 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.

为了最大程度的减少实现这一过程的开销。functools.total_ordering()提供了生成缺少的比较操作的方法。

PEP 207 indicates that reflexivity rules are assumed by Python. Thus, the interpreter may swap y > x with x < yy >= 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 < yy >= x转换为 x <= y，也会转换x == y 和 x != 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.

字符异常在新的代码中被禁止了，因为这一语言特性在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.:

模块或者包应该定义自己的异常基类，这个类应该继承自内置的Exception类。总要包含类文档语句，例如：

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:

try:
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:

经验告诉我们在两个情况下避免使用空‘except’

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 raisetry...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语句来减少必要代码的数量。 再者，可以避免掩盖问题。

Yes:

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


No:

try:
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方法而非String模块

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.

String方法更加快捷并且使用和unicode字符一样的API。如果需要向后兼容2.0之前的版本的话，可以不考虑这条规则。

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

使用''.startswith() 和 ''.endswith()而非字符切片去检测前缀或后缀。

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, reindent.py) will trim them.

书写字面值时不要依靠后面的空格。这些后面的空格，视觉上难以区分，而且很多编辑器（或者，眼前的，reindent.py）会去掉他们。

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

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

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


# References引用

 [1] PEP 7, Style Guide for C Code, van Rossum
 [3] Barry's GNU Mailman style guide http://barry.warsaw.us/software/STYLEGUIDE.txt

This document has been placed in the public domain

03-29 732

09-18 2673

07-21 974

03-24 445

05-18 1640

11-20 5257

07-03 20

05-25 332

02-21 222