Python编码规范PEP-8 by zhiyu v0.0(中英对照全文)

如果不想以后看现在写的代码,感觉一团糟的话,起码掌握PEP-8再开始py吧。
现在,有道翻译一个原文版PEP-8,错别字完善后再写一个精简版,不足之处请留言。PEP-8原文
现在脚注和排版都没弄好、不管了,先去学一波前端(逃)
(还是要继续努力才能阅读完全英文的文档啊。)

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[1]中的C代码中关于C代码的风格指南的相关信息PEP。

This document and PEP 257 (Docstring Conventions) were adapted from Guido’s original Python Style Guide essay, with some additions from Barry’s style guide [2].
本文档和PEP 257(Docstring约定)是根据Guido的Python风格指南文章改编而来的,并添加了Barry的风格指南[2]

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”.
圭多的一个关键洞见是,代码读起来要比写得多。
这里提供的指导方针旨在提高代码的可读性,并使其在Python代码的广泛范围内保持一致。
正如PEP 20所说,“可读性很重要”。

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 the most important.
风格指南是关于一致性的。与此风格指南的一致性很重要。
项目中的一致性更重要。一个模块或函数的一致性是最重要的。然而,知道什么时候是不一致的——有时风格指南建议是不适用的。当你怀疑时,运用你最好的判断力。
看看其他的例子,然后决定什么是最好的。
不要犹豫,尽管发问!

In particular: do not break backwards compatibility just to comply with this PEP!
特别要注意:不要破坏向后兼容性,只是为了遵从这个PEP !

Some other good reasons to ignore a particular guideline:
忽略某条指导方针的其他一些好的理由:

  1. When applying the guideline would make the code less readable, even for someone who is used to reading code that follows this PEP.
  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).
  3. Because the code in question predates the introduction of the guideline and there is no other reason to be modifying that code.
  4. When the code needs to remain compatible with older versions of Python that don’t support the feature recommended by the style guide.

  5. 当应用该指南时,代码可读性就会降低,即使对于那些习惯于阅读这一PEP的代码的人来说也是如此。

  6. 与周围的代码相一致(可能是出于历史原因)——尽管这也是一个清理他人混乱的机会(在真正的XP风格中)。
  7. 因为问题的代码先于指导方针的引入,所以没有其他理由修改该代码。
  8. 当代码需要与老版本的Python兼容时,不支持样式指南推荐的特性。

Code lay-out代码布局

Indentation缩进

Use 4 spaces per indentation level.
每个缩进级别使用4个空格。

Continuation lines should align wrapped elements either vertically using Python’s implicit line joining inside parentheses, brackets and braces, or using a hanging indent [7]. When using a hanging indent the following should be considered; there should be no arguments on the first line and further indentation should be used to clearly distinguish itself as a continuation line.
延续行应该使用Python的内隐连接在圆括号、方括号和括号内,或者使用挂起的缩进[7]来对齐包装元素。在使用悬挂式缩进时,应考虑以下事项;在第一行不应该有任何参数,并且应该使用进一步的缩进来清楚地将自己区分为连续的行。

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)

# Hanging indents should add a level.
# 悬挂的缩进应该增加一个水平。
foo = long_function_name(
    var_one, var_two,
    var_three, var_four)
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)

The 4-space rule is optional for continuation lines.
4空格规则是可选的延续行。


Optional:

# Hanging indents *may* be indented to other than 4 spaces.
# 悬挂缩进*可缩进4个空格内。
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:
当条件一个if语句的一部分足够长要求编写跨多个行,值得注意的是,两个字符的组合关键字(即如果),加上一个空格,加上开括号创建一个自然4空间缩进的后续行多行条件。
这可能会产生与iif语句内嵌套的代码嵌套的视觉冲突,这也会自然地缩进到4个空格中。
这个PEP在如何(或是否)进一步在if - statement内的嵌套套件中直观地区分这类条件行没有明确的位置。
在这种情况下可接受的选择包括但不限于:

# 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
# 添加注释,这将在编辑器中提供一些区别。
# supporting syntax highlighting.
# 支持语法高亮显示。
if (this_is_one_thing and
    that_is_another_thing):
    # Since both conditions are true, we can frobnicate.
    # 既然这两种情况都是真的,我们就可以进行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.)
(也可以看到下面的讨论是在二进制运算符之前还是之后。)

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',
    )

或者它可以在开始多行结构的第一个字符下面排列,如:

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.
Tabs应该单独使用,以保持与已经缩进标签的代码一致。

Python 3 disallows mixing the use of tabs and spaces for indentation.
Python 3不允许混合使用制表符和空格来缩进。

Python 2 code indented with a mixture of tabs and spaces should be converted to using spaces exclusively
Python 2代码的缩进使用了制表符和空格的混合,应该转换为只使用空格。

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!
在使用- t选项调用Python 2命令行解释器时,它会对非法混合制表符和空格的代码发出警告。
使用- tt时,这些警告会变成错误。
强烈推荐这些选项!

Maximum Line Length最大行字符长度

Limit all lines to a maximum of 79 characters.
将所有行限制为最多79个字符。

For flowing long blocks of text with fewer structural restrictions (docstrings or comments), the line length should be limited to 72 characters.
对于具有较少结构限制(docstring或comments)的长条文本,行长度应该限制为72个字符。

Limiting the required editor window width makes it possible to have several files open side-by-side, and works well when using code review tools that present the two versions in adjacent columns.
限制所需的编辑器窗口宽度可以使多个文件并排打开,并且在使用在相邻的列中呈现两个版本的代码评审工具时工作得很好。

The default wrapping in most tools disrupts the visual structure of the code, making it more difficult to understand. The limits are chosen to avoid wrapping in editors with the window width set to 80, even if the tool places a marker glyph in the final column when wrapping lines. Some web based tools may not offer dynamic line wrapping at all.
大多数工具的默认包装会破坏代码的视觉结构,这使得理解起来更加困难。选择的限制是避免将窗口宽度设置为80的编辑器包装,即使该工具在最后一列中放置了标记符号。
一些基于web的工具可能根本不提供动态换行。

Some teams strongly prefer a longer line length. For code maintained exclusively or primarily by a team that can reach agreement on this issue, it is okay to increase the nominal line length from 80 to 100 characters (effectively increasing the maximum length to 99 characters), provided that comments and docstrings are still wrapped at 72 characters.
有些团队更喜欢较长的行长度。
对于只保留或主要由能够在这个问题上达成协议的团队来维护的代码,可以将名义行长度从80个字符增加到100个字符(有效地将最大长度增加到99个字符),如果注释和文档字符串仍然以72个字符包装。

The Python standard library is conservative and requires limiting lines to 79 characters (and docstrings/comments to 72).
Python标准库是保守的,它要求将行限制为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.
包装长行的首选方法是使用Python的隐含行继续在括号、括号和括号内。通过在圆括号中包装表达式,可以在多个行上打破长行。这些应该用于优先使用反斜杠进行行延续。

Backslashes may still be appropriate at times. For example, long, multiple with-statements cannot use implicit continuation, so backslashes are acceptable:
反斜杠有时仍然是合适的。
例如,long,多个with-语句不能使用隐式continuation,所以反斜杠是可以接受的:

with open('/path/to/some/file/you/want/to/read') as file_1, \
     open('/path/to/some/file/being/written', 'w') as file_2:
    file_2.write(file_1.read())

(See the previous discussion on multiline if-statements for further thoughts on the indentation of such multiline with-statements.)
(请参阅前面关于多行if语句的讨论,以进一步了解这种多行语句的缩进。)

Another such case is with assert statements.
另一个这样的例子是断言语句。

Make sure to indent the continued line appropriately.
一定要适当地缩进生产线。

Should a line break before or after a binary operator?在二进制运算符之前或之后有一个行中断吗?

For decades the recommended style was to break after binary operators. But this can hurt readability in two ways: the operators tend to get scattered across different columns on the screen, and each operator is moved away from its operand and onto the previous line. Here, the eye has to do extra work to tell which items are added and which are subtracted:

几十年来,推荐的风格是在二元运算符之后打破。
但这可能会在两方面损害可读性:操作人员倾向于分散在屏幕上的不同列上,并且每个操作符都从操作数转移到上一行。
在这里,眼睛需要做额外的工作来分辨哪些物品被添加了,哪些被减掉了:

# No: operators sit far away from their operands
# 操作员坐在远离他们操作数的地方。
income = (gross_wages +
          taxable_interest +
          (dividends - qualified_dividends) -
          ira_deduction -
          student_loan_interest)

To solve this readability problem, mathematicians and their publishers follow the opposite convention. Donald Knuth explains the traditional rule in his Computers and Typesetting series: “Although formulas within a paragraph always break after binary operations and relations, displayed formulas always break before binary operations” [3].

Following the tradition from mathematics usually results in more readable code:

为了解决这个可读性问题,数学家和他们的出版商遵循着相反的惯例。
Donald Knuth在他的电脑和排字系列中解释了传统的规则:“尽管在一段里的公式总是在二进制运算和关系之后中断,显示的公式总是在二进制运算之前中断”[3]

遵循数学传统通常会产生更可读的代码:

# Yes: easy to match operators with operands
income = (gross_wages
          + taxable_interest
          + (dividends - qualified_dividends)
          - ira_deduction
          - student_loan_interest)

In Python code, it is permissible to break before or after a binary operator, as long as the convention is consistent locally. For new code Knuth’s style is suggested.
在Python代码中,只要该约定在本地是一致的,就允许在二进制操作符之前或之后中断。
提出了新的代码Knuth的风格。

Blank Lines空白行

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

Method definitions inside a class are surrounded 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).

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的代码查看器可能无法识别控件- l作为一个表单提要,并将显示另一个符号。

Source File Encoding源文件编码

Code in the core Python distribution should always use UTF-8 (or ASCII in Python 2).

Files using ASCII (in Python 2) or UTF-8 (in Python 3) should not have an encoding declaration.

In the standard library, non-default encodings should be used only for test purposes or when a comment or docstring needs to mention an author name that contains non-ASCII characters; otherwise, using \x, \u, \U, or \N escapes is the preferred way to include non-ASCII data in string literals.

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 (latin-1, ISO/IEC 8859-1 character set) MUST provide a transliteration of their names in this character set.

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

核心Python发行版中的代码应该总是使用utf - 8(或Python 2中的ASCII)。

使用ASCII(在Python 2中)或utf - 8(在Python 3中)使用的文件不应该有编码声明。

在标准库中,非默认编码应该仅用于测试目的,或者当注释或docstring需要提到包含非ascii字符的作者名称时;
否则,使用\ x \u \u \ \ N转义是在字符串文字中包含非ascii数据的首选方法。

对于Python 3.0和beyond,标准库使用以下策略(参见PEP 3131):在Python标准库中,所有标识符都必须使用ascii标识符,并且应该在可行的地方使用英语单词(在许多情况下,缩写和术语使用的不是英语)。
另外,字符串文字和注释也必须是ASCII的。
唯一的例外是(a)测试非ascii特性的测试用例,以及(b)作者的名字。
那些名字不是基于拉丁字母(Latin - 1,ISO / iec8859 - 1字符集)的作者必须在这个字符集中提供他们的名字的音译。

鼓励全球受众的开放源码项目采用类似的策略。

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
    1. 标准库进口
    2. 相关第三方进口
    3. 本地应用程序特定进口/库

You should put a blank line between each group of imports.
您应该在每个导入组之间设置一个空行。

  • Absolute imports are recommended, as they are usually more readable and tend to be better behaved (or at least give better error messages) if the import system is incorrectly configured (such as when a directory inside a package ends up on sys.path):
  • 建议绝对导入,因为它们通常更易于阅读,而且如果导入系统的配置错误(比如包内的目录在sys . path中结束时),它们的行为会更好(或者至少给出更好的错误消息):
import mypkg.sibling
from mypkg import sibling
from mypkg.sibling import example

However, explicit relative imports are an acceptable alternative to absolute imports, especially when dealing with complex package layouts where using absolute imports would be unnecessarily verbose:
然而,明确的相对进口是绝对进口的可接受的替代方案,特别是在使用绝对进口的复杂的包布局时,这是不必要的冗长:

from . import sibling
from .sibling import example

Standard library code should avoid complex package layouts and always use absolute imports.
标准的库代码应该避免复杂的包布局,并且总是使用绝对的导入。

Implicit relative imports should never be used and have been removed in Python 3.
不应该使用隐式相对导入,并在python3中删除。

  • 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”。

  • Wildcard imports (from <module> import *) should be avoided, as they make it unclear which names are present in the namespace, confusing both readers and many automated tools. There is one defensible use case for a wildcard import, which is to republish an internal interface as part of a public API (for example, overwriting a pure Python implementation of an interface with the definitions from an optional accelerator module and exactly which definitions will be overwritten isn’t known in advance).
  • 应该避免通配符导入(从<模块>导入* *),因为它们不清楚名称空间中存在哪些名称,混淆了读者和许多自动化工具。
    有一个站得住脚的通配符导入用例,这是重新发布一个内部接口作为公共API的一部分(例如,覆盖一个纯Python实现一个接口的定义从一个可选的加速器模块和哪些定义将被重写不是提前知道)。

When republishing names this way, the guidelines below regarding public and internal interfaces still apply.
当以这种方式重新发布名称时,关于公共和内部接口的准则仍然适用。

Module level dunder names

Module level “dunders” (i.e. names with two leading and two trailing underscores) such as __all__, __author__, __version__, etc. should be placed after the module docstring but before any import statements except from __future__ imports. Python mandates that future-imports must appear in the module before any other code except docstrings.
模块级“dunders”(即具有两个前导和两个后继下划线的名称),如__all____author____version__等,应在模块docstring之后放置,但在任何导入语句之前,除了来自__future__的导入。
Python要求未来导入必须在除docstring之外的任何其他代码之前出现在模块中。

For example:
例如:

"""This is the example module.

This module does stuff.
"""

from __future__ import barry_as_FLUFL

__all__ = ['a', 'b', 'c']
__version__ = '0.1'
__author__ = 'Cardinal Biggles'

import os
import sys

String Quotes字符串引号

In Python, single-quoted strings and double-quoted strings are the same. This PEP does not make a recommendation for this. Pick a rule and stick to it. When a string contains single or double quote characters, however, use the other one to avoid backslashes in the string. It improves readability.
在Python中,单引号字符串和双引号字符串是相同的。
这个PEP并没有给出建议。
选择一条规则并坚持到底。
当字符串包含单引号或双引号字符时,使用另一个字符串来避免字符串中的反斜杠。
它提高了可读性。

For triple-quoted strings, always use double quote characters to be consistent with the docstring convention in PEP 257.
对于三引号字符串,总是使用双引号字符来与PEP 257中的docstring约定相一致。

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 } )
  • Between a trailing comma and a following close parenthesis.
  • 在后面的逗号和后面的括号之间。
Yes: foo = (0,)
No:  bar = (0, )
  • 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
  • However, in a slice the colon acts like a binary operator, and should have equal amounts on either side (treating it as the operator with the lowest priority). In an extended slice, both colons must have the same amount of spacing applied. Exception: when a slice parameter is omitted, the space is omitted.
  • 但是,在一个切片中,冒号就像一个二元运算符,在任何一方都应该有相等的数量(将其作为最低优先级的操作符处理)。
    在扩展的切片中,两个冒号必须具有相同的间距。
    例外:当一个切片参数被省略时,空间被忽略。
Yes:

ham[1:9], ham[1:9:3], ham[:9:3], ham[1::3], ham[1:9:]
ham[lower:upper], ham[lower:upper:], ham[lower::step]
ham[lower+offset : upper+offset]
ham[: upper_fn(x) : step_fn(x)], ham[:: step_fn(x)]
ham[lower + offset : upper + offset]
No:

ham[lower + offset:upper + offset]
ham[1: 9], ham[1 :9], ham[1:9 :3]
ham[lower : : upper]
ham[ : upper]
  • 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: dct['key'] = lst[index]
No:  dct ['key'] = lst [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其他建议

  • Avoid trailing whitespace anywhere. Because it’s usually invisible, it can be confusing: e.g. a backslash followed by a space and a newline does not count as a line continuation marker. Some editors don’t preserve it and many projects (like CPython itself) have pre-commit hooks that reject it.
  • 避免尾随空格。
    因为它通常是看不见的,它可能会让人混淆:例如一个反斜杠,后面跟着一个空格,一个换行符不算作一个行连续标记。
    有些编辑器不保存它,许多项目(比如CPython本身)都有预先提交的钩子来拒绝它。
  • 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).
  • 总是将这些二元运算符包围在任何一边:赋值(=),增强赋值(+ =,- =等等),比较(= =,<,>,!
    =、< >、< =、> =,,不,是,不是),布尔值(或者,不是)。
  • If operators with different priorities are used, consider adding whitespace around the operators with the lowest priority(ies). Use your own judgment; however, never use more than one space, and always have the same amount of whitespace on both sides of a binary operator.
  • 如果使用了不同优先级的操作符,考虑在操作符周围添加空格,以最低优先级(ies)。
    用你自己的判断;
    但是,永远不要使用超过一个空格,并且在二元运算符的两边总是有相同数量的空格。
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)
  • Function annotations should use the normal rules for colons and always have spaces around the -> arrow if present. (See Function Annotations below for more about function annotations.)
  • 函数注释应该使用colons的正常规则,如果存在,则在- >箭头周围总是有空格。
    (请参阅下面的函数注释,了解更多关于函数注释的内容。)
Yes:

def munge(input: AnyStr): ...
def munge() -> AnyStr: ...
No:

def munge(input:AnyStr): ...
def munge()->PosInt: ...
  • When combining an argument annotation with a default value, use spaces around the = sign (but only for those arguments that have both an annotation and a default).
  • 当将参数注释与默认值相结合时,在=符号附近使用空格(但只有那些既有注释又有默认值的参数)。
Yes:

def munge(sep: AnyStr = None): ...
def munge(input: AnyStr, sep: AnyStr = None, limit=1000): ...
No:

def munge(input: AnyStr=None): ...
def munge(input: AnyStr, limit = 1000): ...
  • 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()

When to use trailing commas何时使用尾随逗号

Trailing commas are usually optional, except they are mandatory when making a tuple of one element (and in Python 2 they have semantics for the print statement). For clarity, it is recommended to surround the latter in (technically redundant) parentheses.
拖尾逗号通常是可选的,除非在创建一个元素的元组时是强制的(在python2中它们对print语句有语义)。
为了清晰起见,建议将后者包围在(技术冗余的)圆括号中。

Yes:

FILES = ('setup.cfg',)
OK, but confusing:
好的,但是困惑:
FILES = 'setup.cfg',

When trailing commas are redundant, they are often helpful when a version control system is used, when a list of values, arguments or imported items is expected to be extended over time. The pattern is to put each value (etc.) on a line by itself, always adding a trailing comma, and add the close parenthesis/bracket/brace on the next line. However it does not make sense to have a trailing comma on the same line as the closing delimiter (except in the above case of singleton tuples).
当拖尾逗号是多余的,当一个版本控制系统被使用时,它们通常是有用的,当一个值列表、参数列表或导入项目被期望随着时间的推移而扩展时。
模式是将每个值(等等)线本身总是添加一个逗号之后,并添加结束括号/架/撑下一行。
然而,在同一行上有一个尾随逗号,与关闭分隔符(除了上述的单例元组)是没有意义的。

Yes:

FILES = [
    'setup.cfg',
    'tox.ini',
    ]
initialize(FILES,
           error=True,
           )
No:

FILES = ['setup.cfg', 'tox.ini',]
initialize(FILES, error=True,)

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. The first word should be capitalized, unless it is an identifier that begins with a lower case letter (never alter the case of identifiers!).
评论应该是完整的句子。第一个单词应该大写,除非它是一个以小写字母开头的标识符(永远不要更改标识符的情况!)

Block comments generally consist of one or more paragraphs built out of complete sentences, with each sentence ending in a period.
块注释一般由一个或多个段落组成,每个句子以句号结尾。

You should use two spaces after a sentence-ending period in multi- sentence comments, except after the final sentence.
你应该在句子结束后的句子中使用两个空格,除了最后一句。

When writing English, follow Strunk and White.
在写英语的时候,跟着斯特伦克和怀特。

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程序员:请用英语写你的注释,除非你有百分之一百二十的肯定代码永远不会被那些不会说你的语言的人阅读。

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.
内联注释是对同一行的注释。内联注释应该至少从语句中分隔两个空格。它们应该以一个#和一个单独的空间开始。
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.
编写好的文档字符串的约定(a.k.a。
“文档字符串”)在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.
  • 为所有公共模块、函数、类和方法编写文档字符串。
    对于非公共方法,docstring不是必需的,但是您应该有一个注释来描述该方法的功能。
    此注释应该出现在def行之后。
  • PEP 257 describes good docstring conventions. Note that most importantly, the “”” that ends a multiline docstring should be on a line by itself, e.g.:
  • PEP 257描述了良好的docstring约定。
    请注意,最重要的是,结束多行docstring的“”本身应该是一行的,例如:
"""Return a foobang

Optional plotz says to frobnicate the bizbaz first.
"""
  • For one liner docstrings, please keep the closing “”” on the same line.
  • 对于一个班轮,请保持关闭“”“在同一行。

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库的命名约定有点混乱,所以我们永远不会完全一致——尽管如此,这里是目前推荐的命名标准。
新的模块和包(包括第三方框架)应该写在这些标准上,但是现有的库有不同的风格,内部一致性更佳。

Overriding Principle压倒一切的原则

Names that are visible to the user as public parts of the API should follow conventions that reflect usage rather than implementation.
对用户可见的名称作为API的公共部分应该遵循反映使用情况而不是实现的约定。

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(单小写字母)
  • B (single uppercase letter)
  • B(大写字母)
  • 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.
  • 大写的单词(或CapWords,或CamelCase)因为字母的凹凸不平而得名[4]
    这有时也被称为StudlyCaps。
  • Note: When using acronyms in CapWords, capitalize all the letters of the acronym. Thus HTTPServerError is better than HttpServerError.
  • 注意:当使用缩写词时,大写字母的首字母缩写。
    因此,HTTPServerError比HTTPServerError好。
  • 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_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()函数返回一个tuple,它的项目传统上有st_mode、st_size、st_mtime等名称。
(这是为了强调与POSIX系统调用struct的字段的通信,这有助于程序员熟悉它。)

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_leading_UNK:弱“内部使用”指示器。
    从M导入*不导入名称以下划线开头的对象。
  • 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_UNK:当命名一个类属性时,调用名称mangling(在类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”对象或存在于用户控制的名称空间中的属性。
    initimportfile
    从来没有发明这样的名字;
    只使用它们作为文档。

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”(小写字母el)、“O”(大写字母oh)或“I”(大写字母“眼睛”)作为单个字符变量名。

In some fonts, these characters are indistinguishable from the numerals one and zero. When tempted to use ‘l’, use ‘L’ instead.
在某些字体中,这些字符与数字1和0难以区分。当你想用“l”时,用“l”代替。

ASCII CompatibilityASCII 兼容性

Identifiers used in the standard library must be ASCII compatible as described in the policy section of PEP 3131.
标准库中使用的标识符必须与PEP 3131的策略部分中描述的ASCII兼容。

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包也应该有短的、全小写的名称,不过下划线的使用是不鼓励的。

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类名

Class names should normally use the CapWords convention.
类名通常使用CapWords约定。

The naming convention for functions may be used instead in cases where the interface is documented and used primarily as a callable.
函数的命名约定可以在接口被文档化并主要用作可调用的情况下使用。

Note that there is a separate convention for builtin names: most builtin names are single words (or two words run together), with the CapWords convention used only for exception names and builtin constants.
注意,对于builtin名称有一个单独的约定:大多数构建名称都是单个单词(或两个单词一起运行),而CapWords约定仅用于异常名称和构建常量。

Type variable names类型变量名

Names of type variables introduced in PEP 484 should normally use CapWords preferring short names: T, AnyStr, Num. It is recommended to add suffixes _co or _contra to the variables used to declare covariant or contravariant behavior correspondingly. Examples:
在PEP 484中引入的类型变量名通常应该使用CapWords,而不喜欢名称:T、AnyStr、Num .建议将后缀_co或_contra添加到用于声明协变或逆变行为的变量中。
例子:

from typing import TypeVar

VT_co = TypeVar('VT_co', covariant=True)
KT_contra = TypeVar('KT_contra', contravariant=True)

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”).
用于从M导入*中使用的模块应该使用__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. threading.py), to retain backwards compatibility.
mixedCase只允许在已经流行的样式(如thread . py)的上下文中保留向后兼容性。

Function and method arguments函数和方法参数

Always use self for the first argument to instance methods.
总是使用self作为实例方法的第一个参数。

Always use cls for the first argument to class methods.
总是使用cls作为类方法的第一个参数。

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的名称“mangling”规则。

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.
常量通常在模块级别上定义,并在所有大写字母中以突出的分隔词书写。
示例包括MAX_OVERFLOW和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).
这里我们不使用“private”这个术语,因为在Python中没有任何属性是真正的私有的(没有通常不必要的工作量)。

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”)的一部分。有些类被设计为继承,可以扩展或修改类的行为。在设计此类类时,请注意对哪些属性是公共属性做出明确的决定,哪些属性是子类API的一部分,哪些属性真正只用于基类。

With this in mind, here are the Pythonic guidelines:
考虑到这一点,下面是Pythonic指南:

  • 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.
  • 对于简单的公共数据属性,最好只公开属性名称,而不需要复杂的访问器/ mutator方法。
    请记住,Python为将来的增强提供了一条简单的路径,您应该发现一个简单的数据属性需要增长函数行为。
    在这种情况下,使用属性将功能实现隐藏在简单数据属性访问语法后面。
    • Note 1: Properties only work on new-style classes.
    • 注1:属性只适用于新式类。
    • Note 2: Try to keep the functional behavior side-effect free, although side-effects such as caching are generally fine.
    • 注意2:尽量避免功能行为的副作用,尽管缓存这样的副作用通常是好的。
    • Note 3: Avoid using properties for computationally expensive operations; the attribute notation makes the caller believe that access is (relatively) cheap.
    • 注释3:避免使用属性进行计算昂贵的操作;
      属性表示法使调用者相信访问(相对)是便宜的。
  • 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的名称“mangling”算法,在该算法中,类的名称会被破坏到属性名中。
    这有助于避免属性名称冲突,因为子类无意中包含具有相同名称的属性。
    • 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:注意,只有简单的类名才会被用在被损坏的名称中,所以如果一个子类选择了相同的类名和属性名,你仍然可以得到名称冲突。
    • 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.
    • 注2:名称“mangling”可以做出某些用途,如调试和__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:并不是每个人都喜欢被命名为“mangling”。尽量平衡避免意外名称与高级调用者潜在使用的冲突。

Public and internal interfaces公共和内部接口

Any backwards compatibility guarantees apply only to public interfaces. Accordingly, it is important that users be able to clearly distinguish between public and internal interfaces.
任何向后兼容性保证只适用于公共接口。因此,用户必须能够清楚地区分公共接口和内部接口。

Documented interfaces are considered public, unless the documentation explicitly declares them to be provisional or internal interfaces exempt from the usual backwards compatibility guarantees. All undocumented interfaces should be assumed to be internal.
文档化的接口被认为是公开的,除非文档明确声明它们是临时的或内部的接口,而不是通常向后兼容的保证。所有未归档的接口都应该假定为内部接口。

To better support introspection, modules should explicitly declare the names in their public API using the __all__ attribute. Setting __all__ to an empty list indicates that the module has no public API.
为了更好地支持内省,模块应该在公共API中使用__all__属性显式地声明名称。将__all__设置为空列表表明该模块没有公共API。

Even with __all__ set appropriately, internal interfaces (packages, modules, classes, functions, attributes or other names) should still be prefixed with a single leading underscore.
即使有适当的设置,内部接口(包、模块、类、函数、属性或其他名称)仍然应该以一个开头的下划线作为前缀。

An interface is also considered internal if any containing namespace (package, module or class) is considered internal.
如果任何包含名称空间(包、模块或类)被认为是内部的,那么接口也被认为是内部的。

Imported names should always be considered an implementation detail. Other modules must not rely on indirect access to such imported names unless they are an explicitly documented part of the containing module’s API, such as os.path or a package’s __init__ module that exposes functionality from submodules.
导入的名称应该总是被视为实现细节。其他模块不能依赖于对这些输入名称的间接访问,除非它们是包含的模块的API(如os)的显式记录部分。路径或包的__init__模块,它公开子模块的功能。

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. This optimization is fragile even in CPython (it only works for some types) and isn’t present at all in implementations that don’t use refcounting. 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的高效实现就地字符串连接的语句形式+ = b或a = a + b。这种优化是脆弱的甚至在CPython的(只适用于某些类型)和不存在在不使用refcounting实现。在库的性能敏感部分中,应该使用“. 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!
    另外,如果x不是None,也要小心,例如,当测试变量或参数是否默认为None时,则设置为其他值。另一个值可能有一个类型(例如容器),在布尔上下文中可能是假的!
  • Use is not operator rather than not … is. While both expressions are functionally identical, the former is more readable and preferred.
  • 使用不是操作,而不是…
    是多少。
    虽然这两个表达式在功能上是相同的,但前者更具有可读性,而且更受欢迎。
Yes:

if foo is not None:
No:

if not foo is None:
  • 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.
  • 在进行具有丰富比较的排序操作时,最好是实现所有6个操作(__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_订购()decorator提供了一个工具来生成缺少的比较方法。

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 == y和x的参数!
= y .类()和min()操作保证使用<操作符和max()函数使用>操作符。
然而,最好是实现所有六个操作,这样在其他环境中就不会出现混淆。

  • Always use a def statement instead of an assignment statement that binds a lambda expression directly to an identifier.
  • 总是使用def语句而不是将lambda表达式绑定到标识符的赋值语句。
Yes:

def f(x): return 2*x
No:

f = lambda x: 2*x

The first form means that the name of the resulting function object is specifically ‘f’ instead of the generic ‘<lambda>‘. This is more useful for tracebacks and string representations in general. The use of the assignment statement eliminates the sole benefit a lambda expression can offer over an explicit def statement (i.e. that it can be embedded inside a larger expression)
第一个表单的意思是产生的函数对象的名称是专门的“f”而不是通用的“< lambda >”。
这对于一般的回溯和字符串表示更有用。
赋值语句的使用消除了lambda表达式在显式def语句上提供的唯一好处(也就是说,它可以嵌入到更大的表达式中)

  • Derive exceptions from Exception rather than BaseException. Direct inheritance from BaseException is reserved for exceptions where catching them is almost always the wrong thing to do.
  • 从异常而不是BaseException派生异常。
    从BaseException继承的直接继承是为异常保留的,在这些异常中捕获它们几乎总是错误的。
    Design exception hierarchies based on the distinctions that code catching the exceptions is likely to need, rather than the locations where the exceptions are raised. Aim to answer the question “What went wrong?” programmatically, rather than only stating that “A problem occurred” (see PEP 3151 for an example of this lesson being learned for the builtin exception hierarchy)
    根据捕获异常的代码可能需要的区别而设计异常层次结构,而不是异常的位置。
    目的是回答“哪里出了问题?”
    以编程的方式,而不是只说“发生了问题”(参见PEP 3151,为构建异常层次结构学习这一课的示例)
    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 that are used for non-local flow control or other forms of signaling need no special suffix.
    这里应用了类命名约定,不过如果异常是一个错误,则应该将“Error”添加到异常类中。
    非本地流控制或其他形式的信令使用的非错误异常不需要特殊的后缀。
  • Use exception chaining appropriately. In Python 3, “raise X from Y” should be used to indicate explicit replacement without losing the original traceback.
  • 适当地使用异常链接。
    在python3中,“raise X from Y”应该用来表示显式的替换,而不会失去原来的traceback。
    When deliberately replacing an inner exception (using “raise X” in Python 2 or “raise X from None” in Python 3.3+), ensure that relevant details are transferred to the new exception (such as preserving the attribute name when converting KeyError to AttributeError, or embedding the text of the original exception in the new exception message).
    当故意更换内部异常(使用Python 2中“提高X”或“提高X从没有“在Python 3.3 +),确保相关信息转移到新异常(如保护属性名称转换KeyError AttributeError时,或嵌入的文本原始异常在新的异常消息)。
  • When raising an exception in Python 2, use raise ValueError(‘message’) instead of the older form raise ValueError, ‘message’.
  • 当在python2中提出一个异常时,使用raise ValueError(‘message ‘)来代替旧的表单来增加ValueError,’ message ‘。
    The latter form is not legal Python 3 syntax.
    后一种形式不是合法的Python 3语法。
    The paren-using form also means that when the exception arguments are long or include string formatting, you don’t need to use line continuation characters thanks to the containing parentheses.
    使用paren的形式还意味着,当异常参数长或包含字符串格式时,不需要使用包含括号的行延续字符。
  • When catching exceptions, mention specific exceptions whenever possible instead of using a bare except: clause.
    在捕获异常时,只要有可能,只要有可能,就应该提到特定的异常,而不是使用无子句。
    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:).
除了:子句将会捕获SystemExit和KeyboardInterrupt异常,这使得用control - c中断程序变得更加困难,并且可以掩盖其他问题。如果您想捕获所有的异常信号程序错误,请使用除异常之外:(bare除外,除了BaseException之外:)。

A good rule of thumb is to limit use of bare ‘except’ clauses to two cases:
一个很好的经验法则是,将“除”条款的使用限制在两种情况下:

  • If the exception handler will be printing out or logging the traceback; at least the user will be aware that an error has occurred.
  • 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向上传播。试一试……最后,可以更好地处理这种情况。
  • When binding caught exceptions to a name, prefer the explicit name binding syntax added in Python 2.6:
  • 当绑定捕获到一个名称的异常时,更喜欢在Python 2.6中添加的显式名称绑定语法:
try:
    process_data()
except Exception as exc:
    raise DataProcessingFailedError(str(exc))

This is the only syntax supported in Python 3, and avoids the ambiguity problems associated with the older comma-based syntax.
这是Python 3中支持的惟一语法,并避免了与基于逗号的旧语法相关的歧义问题。

  • When catching operating system errors, prefer the explicit exception hierarchy introduced in Python 3.3 over introspection of errno values.
  • 在捕获操作系统错误时,更喜欢在Python 3.3中引入的显式异常层次结构,而不是对errno值的自检。
  • Additionally, for all try/except clauses, limit the try clause to the absolute minimum amount of code necessary. Again, this avoids masking bugs.
  • 此外,对于所有尝试/除子句,将try子句限制为必需的绝对最小代码量。
    同样,这避免了屏蔽错误。
Yes:

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

try:
    # Too broad!
    return handle_value(collection[key])
except KeyError:
    # Will also catch KeyError raised by handle_value()
    return key_not_found(key)
  • When a resource is local to a particular section of code, use a with statement to ensure it is cleaned up promptly and reliably after use. A try/finally statement is also acceptable.
  • 当一个资源是特定的代码段的本地资源时,使用with语句来确保它在使用后得到及时和可靠的清理。
    一个try / finally语句也可以接受。
  • Context managers should be invoked through separate functions or methods whenever they do something other than acquire and release resources. For example:
  • 上下文管理器应该通过单独的函数或方法来调用,而不是在获取和发布资源时使用。
    例如:
Yes:

with conn.begin_transaction():
    do_stuff_in_transaction(conn)
No:

with conn:
    do_stuff_in_transaction(conn)

The latter example doesn’t provide any information to indicate that the __enter__ and __exit__ methods are doing something other than closing the connection after a transaction. Being explicit is important in this case.
后一个示例没有提供任何信息,表明__enter__和__exit__方法正在做一些事情,而不是在事务结束后关闭连接。
在这种情况下,明确是很重要的。

  • Be consistent in return statements. Either all return statements in a function should return an expression, or none of them should. If any return statement returns an expression, any return statements where no value is returned should explicitly state this as return None, and an explicit return statement should be present at the end of the function (if reachable).
  • 在返回语句中保持一致。
    函数中的所有返回语句都应该返回一个表达式,否则它们都不应该返回表达式。
    如果任何返回语句返回一个表达式,则返回没有返回值的任何返回语句,应显式地将其声明为返回None,并在函数的末尾(如果可访问)中出现显式return语句。
Yes:

def foo(x):
    if x >= 0:
        return math.sqrt(x)
    else:
        return None

def bar(x):
    if x < 0:
        return None
    return math.sqrt(x)
No:

def foo(x):
    if x >= 0:
        return math.sqrt(x)

def bar(x):
    if x < 0:
        return
    return math.sqrt(x)
  • 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.
    字符串方法总是更快,并且与unicode字符串共享相同的API。
    如果需要与大于2.0的python向后兼容,则重写此规则。
  • 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()和endswith()比较干净,容易出错。
    例如:
Yes: if foo.startswith('bar'):
No:  if foo[:3] == 'bar':
  • 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, str and unicode have a common base class, basestring, so you can do:
在检查对象是否是字符串时,请记住它也可能是unicode字符串!
在Python 2中,str和unicode有一个通用的基类,basestring,所以您可以这样做:

if isinstance(obj, basestring):

Note that in Python 3, unicode and basestring no longer exist (there is only str) and a bytes object is no longer a kind of string (it is a sequence of integers instead)
注意,在Python 3中,unicode和basestring不再存在(只存在str),而字节对象不再是一种字符串(而是一个整数序列)

  • For sequences, (strings, lists, tuples), use the fact that empty sequences are 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:

Function Annotations函数注释

With the acceptance of PEP 484, the style rules for function annotations are changing.
随着PEP 484的接受,函数注释的样式规则正在改变。
In order to be forward compatible, function annotations in Python 3 code should preferably use PEP 484 syntax. (There are some formatting recommendations for annotations in the previous section.)

The experimentation with annotation styles that was recommended previously in this PEP is no longer encouraged.

However, outside the stdlib, experiments within the rules of PEP 484 are now encouraged. For example, marking up a large third party library or application with PEP 484 style type annotations, reviewing how easy it was to add those annotations, and observing whether their presence increases code understandability.

The Python standard library should be conservative in adopting such annotations, but their use is allowed for new code and for big refactorings.

For code that wants to make a different use of function annotations it is recommended to put a comment of the form:

# type: ignore

near the top of the file; this tells type checker to ignore all annotations. (More fine-grained ways of disabling complaints from type checkers can be found in PEP 484.)
靠近文件顶部;这告诉类型检查器忽略所有注释。(更细粒度的方法禁用投诉类型检查可以发现[PEP 484]。

Like linters, type checkers are optional, separate tools. Python interpreters by default should not issue any messages due to type checking and should not alter their behavior based on annotations.
像linters一样,类型检查器是可选的,单独的工具。默认情况下,Python解释器不应该发出任何由于类型检查而导致的消息,也不应该基于注释改变它们的行为。

Users who don’t want to use type checkers are free to ignore them. However, it is expected that users of third party library packages may want to run type checkers over those packages. For this purpose PEP 484 recommends the use of stub files: .pyi files that are read by the type checker in preference of the corresponding .py files. Stub files can be distributed with a library, or separately (with the library author’s permission) through the typeshed repo [5].
不想使用类型检查的用户可以忽略它们。但是,预计第三方库包的用户可能希望在这些包上运行类型检查器。为了这个目的(PEP 484)(https://www.python.org/dev/peps/pep - 0484)建议使用存根文件:。pyi文件,由类型检查器在相应的优先级读取。py文件。存根文件可以分布式库,或单独(库作者的许可)通过typeshed回购[5]

For code that needs to be backwards compatible, type annotations can be added in the form of comments. See the relevant section of PEP 484 [6].
对于需要向后兼容的代码,可以在注释的形式中添加类型注释。请相关部分PEP 484[6]

References引用

[1]PEP 7, Style Guide for C Code, van Rossum
[2]Barry’s GNU Mailman style guide http://barry.warsaw.us/software/STYLEGUIDE.txt
[3]Donald Knuth’s The TeXBook, pages 195 and 196.
[4]http://www.wikipedia.com/wiki/CamelCase
[5]Typeshed repo https://github.com/python/typeshed
[6]Suggested syntax for Python 2.7 and straddling code https://www.python.org/dev/peps/pep-0484/#suggested-syntax-for-python-2-7-and-straddling-code
[7]悬挂压痕是一种类型设置样式,除了第一行,段落中的所有行都是缩进的。在Python的上下文中,这个术语用来描述一种样式,其中插入式语句的开括号是行的最后一个非空格字符,后面的行是缩进的,直到结束括号为止。

Copyright版权

This document has been placed in the public domain.
该文件已被置于公共领域。
Source: https://github.com/python/peps/blob/master/pep-0008.txt

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
PEP8Python编码规范的官方指南,它旨在提供一种一致的编码风格,以促进代码的可读性和可维护性。它涵盖了代码布局、命名约定、注释、导入语句等方面的规范。 根据PEP8指南[2],以下是一些主要的编码规范要点: 1. 代码布局:使用4个空格作为缩进,不要使用制表符,并将每行代码的长度限制在79个字符以内。适当的缩进和代码对齐可以增强可读性。 2. 命名约定:变量和函数名应该用小写字母,单词之间使用下划线分隔,而不是驼峰命名法。类名应该使用驼峰命名法。 3. 注释:对于复杂的代码块或算法,请添加适当的注释来解释代码的目的和功能。注释应该以句号结尾,并且应该避免在代码中使用无意义或过多的注释。 4. 导入语句:每个导入应该独占一行,并按照标准库模块、第三方库模块和本地应用程序模块的顺序排列。每个模块导入应该写在文件的顶部,并且应该将标准库导入放在其他导入之前。 这只是PEP8指南的一小部分,你可以参考原文了解更多细节和规范。但是需要注意的是,根据中提到的几个理由,有时候可以忽略特定的规则。当遵循规范会降低代码可读性,与周围代码不一致,或需要兼容老版本Python时,可以考虑忽略某些规则。 总结答案: PEP8Python编码规范指南,它包含了代码布局、命名约定、注释和导入语句等方面的规范。它帮助提高代码的可读性和可维护性,使得多人合作开发更加便利。你可以在PEP8的原文中找到更多详细的规范。不过,需要注意的是,有时候根据实际情况,可以忽略特定的规则。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值