文章目錄
-
-
-
- Introduction 引言
- A Foolish Consistency is the Hobgoblin of Little Minds 盡信書不如無書
- Code Lay-out 代碼布局
-
- Indentation 縮進
- Tabs or Spaces? 使用制表符還是空格
- Maximum Line Length 最大行長
- Should a Line Break Before or After a Binary Operator? 在二進制運算符之前還是之後分行?
- Blank Lines 空白行
- Imports 子產品的導入
- Module Level Dunder Names 魔法變量
- String Quotes 字元串引号
- Whitespace in Expressions and Statements 表達式和語句中的空格
-
- Pet Peeves 不能容忍的
- Other Recommendations 其他建議
- When to Use Trailing Commas 何時使用尾随逗号
- Comments 注釋
-
- Block Comments 塊級注釋
- Inline Comments 内聯注釋
- Documentation Strings 文檔字元串
- Naming Conventions 命名約定
-
- Overriding Principle 總的原則
- Descriptive: Naming Styles 描述性: 命名樣式
- 下劃線和變量名
- Prescriptive: Naming Conventions 規定性: 命名約定
-
- Names to Avoid 避免使用的字母
- Package and Module Names 包和子產品名稱
- Class Names 類名
- Type Variable Names 類型變量名
- Exception Names 異常名稱
- Global Variable Names 全局變量名
- Function and Variable Names 函數和變量名
- Function and Method Arguments 函數和方法參數
- Method Names and Instance Variables 方法名和執行個體變量
- Constants 常數
- Designing for Inheritance 為繼承而設計
- Public and Internal Interfaces 公共和内部接口
- Programming Recommendations 程式設計建議
-
- Function Annotations 函數注釋
- Variable Annotations 變量注釋
-
-
官方文檔位址: 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_OVERFLOW
和
TOTAL
。
Designing for Inheritance 為繼承而設計
Always decide whether a class’s methods and instance variables (collectively: “attributes”) should be public or non-public. If in doubt, choose non-public; it’s easier to make it public later than to make a public attribute non-public.
當我們不能決定類的方法和執行個體變量(統稱為"屬性")應該是
public
還是
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