如果不想以后看现在写的代码,感觉一团糟的话,起码掌握PEP-8再开始py吧。
现在,有道翻译一个原文版PEP-8,错别字完善后再写一个精简版,不足之处请留言。PEP-8原文
现在脚注和排版都没弄好、不管了,先去学一波前端(逃)
(还是要继续努力才能阅读完全英文的文档啊。)
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.
许多项目都有自己的编码风格指南。
在发生任何冲突时,这些项目特定的指南优先于该项目。
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:
忽略某条指导方针的其他一些好的理由:
When the code needs to remain compatible with older versions of Python that don’t support the feature recommended by the style guide.
当应用该指南时,代码可读性就会降低,即使对于那些习惯于阅读这一PEP的代码的人来说也是如此。
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',
)
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时,这些警告会变成错误。
强烈推荐这些选项!
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.
一定要适当地缩进生产线。
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的风格。
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作为一个表单提要,并将显示另一个符号。
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字符集)的作者必须在这个字符集中提供他们的名字的音译。
鼓励全球受众的开放源码项目采用类似的策略。
Yes: import os
import sys
No: import sys, os
from subprocess import Popen, PIPE
Imports should be grouped in the following order:
进口应按以下顺序分组:
You should put a blank line between each group of imports.
您应该在每个导入组之间设置一个空行。
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中删除。
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”。
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).When republishing names this way, the guidelines below regarding public and internal interfaces still apply.
当以这种方式重新发布名称时,关于公共和内部接口的准则仍然适用。
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
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约定相一致。
Avoid extraneous whitespace in the following situations:
在下列情况下避免无关空格:
Yes: spam(ham[1], {eggs: 2})
No: spam( ham[ 1 ], { eggs: 2 } )
Yes: foo = (0,)
No: bar = (0, )
Yes: if x == 4: print x, y; x, y = y, x
No: if x == 4 : print x , y ; x , y = y , x
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]
Yes: spam(1)
No: spam (1)
Yes: dct['key'] = lst[index]
No: dct ['key'] = lst [index]
Yes:
x = 1
y = 2
long_variable = 3
No:
x = 1
y = 2
long_variable = 3
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)
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)
Yes:
def munge(input: AnyStr): ...
def munge() -> AnyStr: ...
No:
def munge(input:AnyStr): ...
def munge()->PosInt: ...
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): ...
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()
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()
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 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 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 #.
块注释中的段落由包含一个#的行分隔。
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
Conventions for writing good documentation strings (a.k.a. “docstrings”) are immortalized in PEP 257.
编写好的文档字符串的约定(a.k.a。
“文档字符串”)在PEP 257中被永久保存。
"""Return a foobang
Optional plotz says to frobnicate the bizbaz first.
"""
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库的命名约定有点混乱,所以我们永远不会完全一致——尽管如此,这里是目前推荐的命名标准。
新的模块和包(包括第三方框架)应该写在这些标准上,但是现有的库有不同的风格,内部一致性更佳。
Names that are visible to the user as public parts of the API should follow conventions that reflect usage rather than implementation.
对用户可见的名称作为API的公共部分应该遵循反映使用情况而不是实现的约定。
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:
以下的命名方式通常是有区别的:
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):
此外,使用前导或尾下划线的特殊表单可以被识别(通常可以与任何情况约定相结合):
Tkinter.Toplevel(master, class_='ClassName')
__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.
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”代替。
Identifiers used in the standard library must be ASCII compatible as described in the policy section of PEP 3131.
标准库中使用的标识符必须与PEP 3131的策略部分中描述的ASCII兼容。
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 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约定仅用于异常名称和构建常量。
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)
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”(如果异常实际上是一个错误)。
(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 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)的上下文中保留向后兼容性。
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好。(最好是使用同义词来避免这种冲突。)
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 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。
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指南:
公共属性应该没有下划线。
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.)
__getattr__()
, less convenient. However the name mangling algorithm is well documented and easy to perform manually.__getattr__()
,不太方便。 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__
模块,它公开子模块的功能。
Yes:
if foo is not None:
No:
if not foo is None:
__eq__
, __ne__
, __lt__
, __le__
, __gt__
, __ge__
) rather than relying on other code to only exercise a particular comparison.__eq__
,__ne__
,__lt__
,__le__
,__gt__
,__ge__
),而不是依赖其他代码来进行特定的比较。 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()函数使用>操作符。
然而,最好是实现所有六个操作,这样在其他环境中就不会出现混淆。
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语句上提供的唯一好处(也就是说,它可以嵌入到更大的表达式中)
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:
一个很好的经验法则是,将“除”条款的使用限制在两种情况下:
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中支持的惟一语法,并避免了与基于逗号的旧语法相关的歧义问题。
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)
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__
方法正在做一些事情,而不是在事务结束后关闭连接。
在这种情况下,明确是很重要的。
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)
Yes: if foo.startswith('bar'):
No: if foo[:3] == 'bar':
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),而字节对象不再是一种字符串(而是一个整数序列)
Yes: if not seq:
if seq:
No: if len(seq):
if not len(seq):
Yes: if greeting:
No: if greeting == True:
Worse: if greeting is True:
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]。
[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的上下文中,这个术语用来描述一种样式,其中插入式语句的开括号是行的最后一个非空格字符,后面的行是缩进的,直到结束括号为止。 |
This document has been placed in the public domain.
该文件已被置于公共领域。
Source: https://github.com/python/peps/blob/master/pep-0008.txt