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

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

大家好,我是讯享网,很高兴认识大家。

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

Introduction介绍

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

  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缩进

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) 

讯享网
讯享网 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()
讯享网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?

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最大行字符长度

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个字符包装。

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

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:

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

讯享网# 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接受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中)使用的文件不应该有编码声明。

对于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.
  • 导入总是放在文件的顶部,在任何模块注释和文档字符串之后,以及在模块全局和常量之前。
    1. standard library imports
    2. related third party imports
    3. local application/library specific imports
    1. 标准库进口
    2. 相关第三方进口
    3. 本地应用程序特定进口/库
  • 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
讯享网from . import sibling from .sibling import example
  • 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
讯享网import myclass import foo.bar.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实现一个接口的定义从一个可选的加速器模块和哪些定义将被重写不是提前知道)。

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之外的任何其他代码之前出现在模块中。

"""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并没有给出建议。
选择一条规则并坚持到底。
当字符串包含单引号或双引号字符时,使用另一个字符串来避免字符串中的反斜杠。
它提高了可读性。

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

Pet Peeves厌恶的东西

  • 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,但不要在多个子句语句中这样做。
    还要避免折叠这么长的线条!
讯享网if foo == 'blah': do_blah_thing() for x in lst: total += x while t < 10: t = delay()


讯享网

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注释

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
讯享网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压倒一切的原则

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.
有很多不同的命名风格。
它有助于识别使用什么命名风格,独立于它们的用途。

  • 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中,这种样式通常被认为是不必要的,因为属性和方法名称是用对象前缀的,而函数名是用模块名前缀的。

  • _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名称,以避免

ASCII CompatibilityASCII 兼容性

Package and Module Names包和模块名称

Class Names类名

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全局变量名

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 and method arguments函数和方法参数

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

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设计继承

  • 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公共和内部接口

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.
即使有适当的设置,内部接口(包、模块、类、函数、属性或其他名称)仍然应该以一个开头的下划线作为前缀。

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

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

小讯
上一篇 2025-02-05 17:48
下一篇 2025-02-28 10:04

相关推荐

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/24103.html