Python——PEP 8 代码风格规范

文章目录


官方文档地址: https://www.python.org/dev/peps/pep-0008/#other-recommendations

Introduction 引言

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.

许多项目都有自己的编码风格指南。 如果发生任何冲突,项目的代码规范优先于 PEP8。

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所说,“可读性很重要”。

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.

风格指南是关于一致性的。 与这个风格指南保持一致很重要。 项目中的一致性更为重要。 一个模块或者功能的一致性是最重要的。

However, know when to be inconsistent – sometimes style guide recommendations just aren’t applicable. When in doubt, use your best judgment. Look at other examples and decide what looks best. And don’t hesitate to ask!

然而,知道什么时候是不一致的---- 有时风格指南的建议是不适用的。 当有疑问的时候,用你最好的判断。 看看其他的例子,然后决定什么看起来最好。 不要犹豫,尽管开口!

In particular: do not break backwards compatibility just to comply with this PEP!

特别地: 不要为了遵守这个 PEP 而破坏向后兼容性!

Some other good reasons to ignore a particular guideline:

还有一些理由可以让你忽略某个特定的指导方针:

When applying the guideline would make the code less readable, even for someone who is used to reading code that follows this PEP. 当应用该准则时,即使对于习惯于阅读遵循此 PEP 的代码的人来说,代码的可读性也会降低
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 风格)
Because the code in question predates the introduction of the guideline and there is no other reason to be modifying that code. 因为有问题的代码是在准则引入之前,并且没有其他理由要修改该代码
When the code needs to remain compatible with older versions of Python that don’t support the feature recommended by the style guide. 当代码需要与不支持样式指南推荐的特性的旧版本 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-space 规则是可选的。

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:

当 if 语句的条件部分足够长,需要跨多行编写时,值得注意的是,两个字符关键字(即 if)加上一个空格,再加上一个括号,就可以为多行条件的后续行创建一个自然的4空格缩进。 这可能会与嵌套在 if 语句中的缩进代码组产生视觉冲突,这些代码组自然也会缩进为4个空格。 这个 PEP 没有明确说明如何(或是否)从 if-语句内的嵌套中进一步可视地区分这种条件行。 在这种情况下可接受的选择包括但不限于:

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

Tabs 应该只用于保持与已经缩进了选项卡的代码的一致性。

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.

对于结构限制较少的长文本块(文档字符串或注释) ,行长应限制为72个字符。

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

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

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

遵循数学的传统,代码通常更具可读性:

# 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 作为一个表单提要,并将在其位置显示另一个字形。

Imports 模块的导入

Imports should usually be on separate lines:

导入通常应该分开写:

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.

您应该在每组导入之间放置一个空行。

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

推荐使用绝对导入,因为如果导入系统配置错误(例如包中的目录最终出现在 syspath 中) ,绝对导入通常更具可读性,性能更好(或者至少给出更好的错误消息:

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.

隐式相对导入永远不应该使用,并且已经在 Python 3中删除了。

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

如果此拼写导致本地名称冲突,则显式拼写它们:

import myclass
import foo.bar.yourclass

and use “myclass.MyClass” and “foo.bar.yourclass.YourClass”.

并使用"myclass.MyClass"和"foo.bar.yourclass.YourClass"。

Wildcard imports (from 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 的一部分重新发布(例如,使用可选的 accelerator 模块中的定义覆盖一个纯 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 之后,但是除了将来导入的导入语句之外,任何导入语句之前。 Python 要求 future-import 必须在模块中出现在除 docstrings 之外的任何其他代码之前:

"""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中的文档字符串约定。

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

总是在这些二元操作符的两边各放一个空格:

赋值:=
增量赋值:+=, -=等
比较:==, <, >, !=, <>, <=, >=, in, not in, is, is not
布尔: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.

如果使用了具有不同优先级的操作符,请考虑在优先级最低的操作符周围添加空格。 使用您自己的判断,但是,从来没有使用一个以上的空格,并始终有相同数量的空格双方的二进制运算符。

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)

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

函数注释应该使用冒号的普通规则,并且如果存在的话,应该在箭头周围设置空格。 (有关函数注释的更多信息,请参见下面的函数注释。)

Yes:

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

No:

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

Don’t use spaces around the = sign when used to indicate a keyword argument, or when used to indicate a default value for an unannotated function parameter.

当用于指示关键字参数或用于指示未加注释的函数参数的默认值时,不要在符号周围使用空格。

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)

When combining an argument annotation with a default value, however, do use spaces around the = sign:

但是,在将参数注释与默认值组合时,请在符号周围使用空格:

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.

尾随逗号通常是可选的,除了在创建一个元素的元组时是必须的(在 Python 2 中,它们对于 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.

在多句注释中,除了最后一句之后,你应该在句尾句之后使用两个空格。

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

来自非英语国家的 Python 程序员: 请用英语写您的评论,除非您有120% 的把握这些代码永远不会被不会说您的语言的人读到。

Block Comments 块级注释

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

块注释通常应用于一些(或全部)跟随它们的代码,并缩进到与该代码相同的级别。 块注释的每一行都以一个 # 和一个空格开头(除非注释中缩进了文本)。

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

块注释中的段落由包含单个 # 的行分隔。

Inline Comments 内联注释

Use inline comments sparingly.

谨慎使用内联注释。

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

内联注释是与语句在同一行上的注释。 内联注释与语句之间至少应该隔两个空格。 他们应该从一个 # 和一个单独的空间开始。

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.

编写良好文档字符串的约定(又称"文档字符串")在 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.

为所有公共模块、函数、类和方法编写文档字符串。 对于非公共方法来说,Docstrings 是不必要的,但是你应该有一个注释来描述这个方法的功能。 这个注释应该出现在 def 行之后。

PEP 257 describes good docstring conventions. Note that most importantly, the """ that ends a multiline docstring should be on a line by itself:

257描述了良好的文档字符串约定。 请注意,最重要的是,结束多行文档字符串的"""字符本身应该在一行上:

"""Return a foobang

Optional plotz says to frobnicate the bizbaz first.
"""

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 (single uppercase letter)    单个大写字母

lowercase                      全小写

lower_case_with_underscores    使用下划线的全小写

UPPERCASE                      全大写

UPPER_CASE_WITH_UNDERSCORES    使用下划线的全大写

CapitalizedWords               大驼峰命名

mixedCase                      混合大小写

Capitalized_Words_With_Underscores    使用下划线的全首字母大写(丑!!!)
下划线和变量名

单下划线的_xxx 的成员变量叫做保护变量,意思是只有类对象和子类对象自己能访问到这些变量,且不能通过from module import *导入,需通过类提供的接口进行访问。

双下划线的__xxx 是私有变量,只有类对象自己能访问,连子类对象也不能访问到这个数据。

__xxx__ 为内置的特殊变量或函数,如 __init__()是类的构造函数。

单下划线后缀xxx_,通常用来避免与 Python 关键字冲突,如class_

Prescriptive: Naming Conventions 规定性: 命名约定
Names to Avoid 避免使用的字母

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

永远不要使用字符"l"(L 的小写) ,“O”(o 的大写)或"I"(大写的 i)作为单字符变量名称。

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

在某些字体中,这些字符与数字1和0难以区分。 当试图使用’l’时,用’L’代替。

Package and Module Names 包和模块名称

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

模块的名称应该是短小写。 如果下划线提高了可读性,则可以在模块名中使用它。 Python 包还应该使用短小写的名称,尽管不鼓励使用下划线。

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

class Animal:
	psss

class MyAnimal:
	pass

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.

注意,内建名称有一个单独的约定: 大多数内建名称是单个单词(或两个单词一起运行) ,CapWords 约定只用于异常名称和内建常量。

因此,一些内置的类,首字母都是小写,而实例都是大写。

比如 bool 是类名,而 True,False 是其实例;

比如 ellipsis 是类名,Ellipsis是实例;

还有 int,string,float,list,tuple,dict 等一系列数据类型都是类名,它们都是小写。

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:

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 and Variable Names 函数和变量名

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

函数名应该是小写的,必要时用下划线分隔,以提高可读性。

def speak():
	pass

def speak_to_someone():
	pass

Variable names follow the same convention as function names.

变量名遵循与函数名相同的约定。

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

只有在已经成为主流风格的情况下(例如 threading.py) ,才允许 mixedCase 保持向后兼容性。

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.

对于 class 方法的第一个参数总是使用 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.)

如果函数参数的名称与保留关键字冲突,通常最好附加一个下划线,而不是使用缩写或拼写错误。 因此,上流社会比下流社会好。 (或许使用同义词来避免这种冲突会更好。)

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 的名称管理规则。

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 访问。 (一个坚持的用户仍然可以通过调用 Foo 获得访问权限。 通常,双前导下划线应该只用于避免与设计用于子类化的类中的属性的名称冲突。

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_OVERFLOWTOTAL

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还是non-public,尽量选择no-public。因为把non-public改为public,比把public改为non-public更容易。

Public attributes are those that you expect unrelated clients of your class to use, with your commitment to avoid backwards 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).

在这里我们不使用术语"私有",因为在 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.

另一类属性是"子类 API"的一部分(在其他语言中通常称为"protected")。 有些类被设计为从中继承,用于扩展或修改类行为的各个方面。 在设计这样的类时,要注意做出明确的决定,哪些属性是公共的,哪些属性是子类 API 的一部分,哪些属性只能由基类使用。

With this in mind, here are the Pythonic guidelines:

考虑到这一点,下面是 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.

对于简单的公共数据属性,最好只公开属性名,而不要使用复杂的 accessor / 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 的名称破坏算法,其中类的名称被破坏到属性名称。 这有助于避免属性名冲突,避免子类无意中包含具有相同名称的属性。

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.

注意: 注意,只有简单的类名在错误的名称中使用,所以如果一个子类同时选择相同的类名和属性名,您仍然可以获得名称冲突。

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: 名称改动可能会使某些用途,比如调试和 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: 不是每个人都喜欢名字被改错。 在避免名称意外冲突的需要与高级调用方可能的使用之间,尽量保持平衡。

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.

为了更好地支持自省,模块应该使用 all 属性在其公共 API 中明确声明名称。 将 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.path 或者公开子模块功能的包的 init 模块。

Programming Recommendations 编程建议

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

从 Exception 而不是 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应该用于表示显式替换而不会丢失原始回溯。

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中使用"raise x"或在 Python 3.3 + 中使用"raise x from None")时,确保相关细节传递到新异常(例如在将 KeyError 转换为 AttributeError 时保留属性名,或在新异常消息中嵌入原始异常的文本)。

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

捕捉异常时,尽可能提到特定的异常,而不是使用完全的 except: 子句:

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

Bare except: 子句将捕获 SystemExit 和 KeyboardInterrupt 异常,使用 Control-C 更难中断程序,并可能掩盖其他问题。 如果您想要捕获所有发出程序错误信号的异常,请使用 Exception: (bare except 等效于 BaseException:)。

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

一个很好的经验法则是将纯粹"except"子句的使用限制在两种情况下:

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. 可能是处理这个案子更好的方法
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.

在捕获操作系统错误时,比起内省 errno 值,更喜欢 Python 3.3中引入的显式异常层次结构。

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

每当上下文管理器执行除获取和释放资源之外的任务时,都应该通过单独的函数或方法调用它们。

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

在回报表中保持一致。 要么函数中的所有 return 语句都应该返回一个表达式,要么它们都不应该返回。 如果任何 return 语句返回一个表达式,任何没有返回值的返回语句都应该显式地声明为 return None,并且在函数的末尾应该有一个显式的返回语句(如果可以访问)。

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

使用"。 和"开始"。 Endswith ()代替字符串切片来检查前缀或后缀。

startswith() and endswith() are cleaner and less error prone:

Startswith ()和 endswith ()更干净,更不容易出错:

Yes:

if foo.startswith('bar'):
	pass

No:

if foo[:3] == 'bar':
	pass

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

对象类型比较应该始终使用 isinstance () ,而不是直接比较类型。

Yes:

if isinstance(obj, int):
	pass

No:

if type(obj) is type(1):
	pass

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 字符串! 在 python2中,str 和 unicode 有一个通用的基类 basestring,所以您可以:

if isinstance(obj, basestring):
	pass

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 和基本字符串不再存在(只有 str) ,字节对象不再是一种字符串(而是一个整数序列)。

For sequences, (strings, lists, tuples), use the fact that empty sequences are false.

对于序列(字符串、列表、元组) ,使用空序列为 false 的事实。

Yes:

if not seq:
	if seq:
		pass

No:

if len(seq):
	if not len(seq):
		pass

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

不要将 boolean 值与 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.)

为了兼容转发,Python 3代码中的函数注释最好使用 PEP 484语法。 (在前一节中有一些针对注释的格式化建议。)

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

Python 标准库在采用此类注释时应该保守一些,但允许在新代码和大规模重构时使用此类注释。

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.

像碎片一样,类型检测器是可选的,独立的工具。 由于类型检查,默认的 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建议使用存根文件:。 类型检查器优先于相应的。 Py 文件。 Stub 文件可以通过库来分发,或者(在库作者的许可下)通过类型为 repo 来分发[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]。

Variable Annotations 变量注释

PEP 526 introduced variable annotations. The style recommendations for them are similar to those on function annotations described above:

Pep 526引入了变量注释。 它们的样式建议与上面描述的函数注释类似:

Annotations for module level variables, class and instance variables, and local variables should have a single space after the colon.

模块级变量、类和实例变量以及局部变量的注释应该在冒号后面有一个空格。

There should be no space before the colon.

结肠前应该没有空格。

If an assignment has a right hand side, then the equality sign should have exactly one space on both sides.

如果赋值符号有右边,那么等号的两边应该正好有一个空格。

Yes:

code: int

class Point:
    coords: Tuple[int, int]
    label: str = '<unknown>'

No:

code:int  # No space after colon
code : int  # Space before colon

class Test:
    result: int=0  # No spaces around equality sign

猜你喜欢

转载自blog.csdn.net/weixin_37641832/article/details/84875741