PEP8, Python代碼書寫風(fēng)格指導(dǎo)

Introduction

This document gives coding conventions for the Python code comprising the standard library in the main Python distribution. Please see the companion informational PEP describing style guidelines for the C code in the C implementation of Python [1].

這篇文檔為Python編程(包括Python主要版本中的標(biāo)準(zhǔn)庫)提供編程的慣用約定. 請參考Python的C語言實現(xiàn)中的, 描述C語言編程風(fēng)格規(guī)范的PEP[1].

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 Conventions>)是由Guido的<Python Style Guide>和Barry的編碼風(fēng)格規(guī)范的部分內(nèi)容改編[2].

This style guide evolves over time as additional conventions are identified and past conventions are rendered obsolete by changes in the language itself.

編碼風(fēng)格規(guī)范隨著時間會有所變化, 因為隨著語言自身的更迭, 會產(chǎn)生新的慣用約定, 廢棄舊的慣用約定.

Many projects have their own coding style guidelines. In the event of any conflicts, such project-specific guides take precedence for that project.

很多項目有他們自己的編程風(fēng)格規(guī)范. 對于沖突的地方, 以項目的風(fēng)格為優(yōu)先.

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的核心觀點是閱讀代碼遠(yuǎn)多于書寫代碼. 這里提供的指導(dǎo)目的在于提高代碼的可讀性和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.

風(fēng)格指導(dǎo)與一致性息息相關(guān). 書寫與此指導(dǎo)風(fēng)格一致的代碼很重要. 書寫與項目風(fēng)格一致的代碼更加重要. 在一個模塊或函數(shù)內(nèi), 書寫風(fēng)格一致的代碼超級重要.

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!

然而, 必須要知道什么時候可以去寫不一致的風(fēng)格--有時候風(fēng)格指導(dǎo)并不適用. 困惑的話就遵從你自己. 多看看別的例子, 自己決定怎么寫最好看. 多問!

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

尤其要注意, 不要為了保持和這篇PEP一致而破壞和過去代碼風(fēng)格的兼容性.

Some other good reasons to ignore a particular guideline:

這里有一些可以無視特定規(guī)范的情形:

  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.
  1. 遵循這個PEP會讓代碼對于一般人, 甚至習(xí)慣于閱讀此PEP規(guī)范代碼的人的可讀性變差這種情況.
  2. 為了與上下文代碼風(fēng)格一致(當(dāng)上下文的風(fēng)格也違背了這個PEP, 可能由于歷史原因etc), 當(dāng)然這也是一個規(guī)范代碼風(fēng)格的機(jī)會(改變上下文的風(fēng)格).
  3. 早于這篇PEP的, 并且沒有理由去修改的代碼.
  4. 需要保持與不支持這些風(fēng)格指導(dǎo)的Python早期版本的兼容性的代碼.

Code lay-out

Indentation

Use 4 spaces per indentation level.

$每層縮進(jìn)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.

分行應(yīng)該按包裹的元素對齊, 要么按括號, 內(nèi)部空間對齊, 要么懸掛縮進(jìn). 如果懸掛縮進(jìn)[7]. 要考慮這些: 參數(shù)不放在首行, 后面的縮進(jìn)要和懸掛縮進(jìn)有明顯區(qū)分.

Yes:

# Aligned with opening delimiter.
# 與括號內(nèi)部空間對齊.
foo = long_function_name(var_one, var_two,
                         var_three, var_four)

# More indentation included to distinguish this from 
the rest.
# 用更多的懸掛縮進(jìn)與后面的語句區(qū)分.
def long_function_name(
        var_one, var_two, var_three,
        var_four):
    print(var_one)

# Hanging indents should add a level.
# 懸掛縮進(jìn)多縮進(jìn)一個層級(4空格).
foo = long_function_name(
    var_one, var_two,
    var_three, var_four)

No:

# Arguments on first line forbidden when not using 
vertical alignment.
# 不用括號內(nèi)部對齊的話, 第一行不應(yīng)該放參數(shù).
foo = long_function_name(var_one, var_two,
    var_three, var_four)

# Further indentation required as indentation is not distinguishable.
# 需要多一層懸掛縮進(jìn)以區(qū)分.
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.
# 懸掛縮進(jìn)可以不是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:

當(dāng)if語句長到必須分行時, 注意到if+空格+括號正好是4空格, 這可能會和if里的執(zhí)行語句的縮進(jìn)沖突, 這篇PEP不提供什么區(qū)分標(biāo)準(zhǔn), 有以下不錯的方法:

# No extra indentation.
# 沒有額外懸掛縮進(jìn)
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.
# 加額外的懸掛縮進(jìn)
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.)

(參見下面的關(guān)于是應(yīng)該在二元操作符前還是后換行的討論)

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:

或和這個多行結(jié)構(gòu)的首字符對齊, 如下:

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.

用空格縮進(jìn)是推薦的做法.

Tabs should be used solely to remain consistent with code that is already indented with tabs.

$除非你要與老代碼保持一致, 否則不要用tab縮進(jìn).

Python 3 disallows mixing the use of tabs and spaces for indentation.

Python3不允許混合空格和tab來縮進(jìn).

Python 2 code indented with a mixture of tabs and spaces should be converted to using spaces exclusively.

Python2的混合縮進(jìn)應(yīng)該要改寫成空格縮進(jìn).

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!

調(diào)用Python2命令時候加上-t參數(shù), 混合縮進(jìn)會有警告, 加上-tt參數(shù), 混合縮進(jìn)會被報錯, 這兩個參數(shù)建議你使用.

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.

對于那種長文本塊(如文檔注釋和注釋), 行長度應(yīng)該被限制在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.

把編輯器寬度調(diào)成窄一點, 這可以并排打開多個文件, 而且能很好的使用代碼檢查工具(這個工具會在相鄰兩列比較兩個版本的文件).

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.

大多數(shù)工具的默認(rèn)的換行設(shè)定打破了代碼的視覺效果, 讓代碼難以理解. 代碼寬度限制就是為了避免在編輯器寬度設(shè)為80時的代碼換行效果, 即便工具折疊功能會在行尾有個標(biāo)志符號. 有些網(wǎng)頁端的工具可能沒有提供動態(tài)的換行設(shè)定.

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.

一些團(tuán)隊非常推崇長的行長度. 如果代碼只由或主要由他們維護(hù)和他們內(nèi)部也打成一致的話, 這種做法也OK, 當(dāng)然注釋啥的還是要維持在72字符以內(nèi)的.

The Python standard library is conservative and requires limiting lines to 79 characters (and docstrings/comments to 72).

Python標(biāo)準(zhǔn)包的寫法完全遵守行長度的限制.

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的隱式連接法--長行可以寫成由括號包裹的短行. 這個方法優(yōu)先于使用\換行.

Backslashes may still be appropriate at times. For example, long, multiple with-statements cannot use implicit continuation, so backslashes are acceptable:

有時候\也是被推薦的用法, 比如長的, 多的 with語句不能使用隱式行連接, 這時候使用\是可以的.

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

(參見前面的關(guān)于多行的if語句的討論, 思考多行with語句的縮進(jìn)方法)

Another such case is with assert statements.

另一個類似的情況是assert語句.

Make sure to indent the continued line appropriately.

確認(rèn)后續(xù)的行縮進(jìn)正常.

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:

數(shù)十年來, 建議的風(fēng)格是在二元操作符后換行. 但這會損害可讀性, 兩個方面: 操作符分散, 操作符和操作數(shù)分離. 眼睛累.

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

為了解決這個可讀性問題, 數(shù)學(xué)家和出版商遵循了另一種慣用約定. Donald Knuth在<Computers and Typesetting>系列說明了這種慣用約定(懶得翻譯).

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

遵循數(shù)學(xué)界的傳統(tǒng), 于是有了更可讀的代碼.

# 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的風(fēng)格.

Blank Lines

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

頂層函數(shù)和類前后空兩行.

Method definitions inside a class are surrounded by a single blank line.

類內(nèi)的方法前后空一行.

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

$可以保守的使用空行來分隔函數(shù)組. 單行的, 相互關(guān)聯(lián)的函數(shù)(如匿名函數(shù))之間不需要空行隔開.

Use blank lines in functions, sparingly, to indicate logical sections.

$在函數(shù)內(nèi)部保守的用空行來分隔邏輯塊.

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處理為空格; 很多工具將它當(dāng)做換頁符, 你可以作為文件分頁標(biāo)記. 注意, 有些編輯器和代碼瀏覽器可能不支持.

Source File Encoding

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

文件采用UTF-8編碼(或者Python2使用ASCII編碼)

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

Python2使用ASCII, 或Python3使用UTF-8編碼, 不需要有編碼聲明.

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.

標(biāo)準(zhǔn)包中, 不能使用非默認(rèn)編碼, 除非: 測試用途, 或者注釋或文檔注釋要提及非ASCII編碼的字符. 一般而言, 使用\x,\u,\U,\N.

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.

Python3或更高版本, 對于標(biāo)準(zhǔn)包有以下這些政策(見PEP 3131): 變量名必須使用ASCII字符, 和(如果可用)使用英文字符(很多情況下會有非英語的縮寫和術(shù)語). 除此之外, 字符串和注釋也必須是ASCII字符, 除了: (a)測試非ASCII字符, (b)作者姓名, 作者的姓名如果不是拉丁字母, 必須有在改字母集下的翻譯.

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

鼓勵有著全球用戶的開源項目也遵循以上政策.

Imports

Imports should usually be on separate lines, e.g.:

$導(dǎo)入語句應(yīng)該單獨(dú)列一行, 如:

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

$導(dǎo)入語句永遠(yuǎn)放置在文件頂部, 模塊注釋或文檔注釋之后, 模塊全局變量和常量之前.

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.

導(dǎo)入應(yīng)該有以下順序:

  1. 標(biāo)準(zhǔn)包
  2. 相關(guān)的第三方包
  3. 本地應(yīng)用\包,

不同組的導(dǎo)入用一行隔開

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

建議絕對路徑導(dǎo)入, 因為這樣通常更加易讀, 也會在導(dǎo)入系統(tǒng)被錯誤配置(如包里的文件路徑以sys.path結(jié)尾)有更好的表現(xiàn)(至少可以提供更好的報錯信息).

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:
顯性相對導(dǎo)入也可以接受, 尤其是當(dāng)處理比較復(fù)雜的包布局, 而絕對導(dǎo)入太冗長.

from . import sibling
from .sibling import example

Standard library code should avoid complex package layouts and always use absolute imports.

標(biāo)準(zhǔn)包代碼應(yīng)該避免復(fù)雜的包布局, 保證總是使用絕對導(dǎo)入.

Implicit relative imports should never be used and have been removed in Python 3.

隱性的相對導(dǎo)入已經(jīng)在Python3中被移除.

When importing a class from a class-containing module, it's usually okay to spell this:

當(dāng)從模塊導(dǎo)入類時, 可以這樣:

from myclass import MyClass
from foo.bar.yourclass import YourClass

If this spelling causes local name clashes, then spell them

如果導(dǎo)致了命名沖突, 則:

import myclass
import foo.bar.yourclass

and use "myclass.MyClass" and "foo.bar.yourclass.YourClass".

Wildcard imports (from <module> import *) should be avoided, as they make it unclear which names are present in the namespace, confusing both readers and many automated tools. There is one defensible use case for a wildcard import, which is to republish an internal interface as part of a public API (for example, overwriting a pure Python implementation of an interface with the definitions from an optional accelerator module and exactly which definitions will be overwritten isn't known in advance).

避免這樣寫from <module> import *, 因為他們不能明晰表示命名空間中存在什么名稱, 是讀者和自動化工具困惑. 有一種情形成為保留這種方式的原因: 就是發(fā)布一個內(nèi)部的接口作為公共API(如重寫一個純Python實現(xiàn), 需要引用到別的模塊的命名, 而這些命名并不被預(yù)先知道).

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.

$模塊級的超級方法(開頭結(jié)尾都有__的方法, 如 __all__, __author__, __version__等), 應(yīng)該在模塊文檔注釋之后, 導(dǎo)入語句之前(除了__future__導(dǎo)入). Python認(rèn)定__future__導(dǎo)入必須出現(xiàn)在模塊中任何其他代碼之前(除了文檔注釋).

For example:

例如:

"""This is the example module.

This module does stuff.
"""

from __future__ import barry_as_FLUFL

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

import os
import sys

String Quotes

In Python, single-quoted strings and double-quoted strings are the same. This PEP does not make a recommendation for this. Pick a rule and stick to it. When a string contains single or double quote characters, however, use the other one to avoid backslashes in the string. It improves readability.

'"在Python中是不區(qū)分的, 在這PEP種也不作區(qū)別, 保持自身一致就行, 如果遇到在字符串中有引號的情況, 優(yōu)先避免使用\.

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.
  • 然而有些情況, 冒號表現(xiàn)為二元操作符(作為最低級的), 應(yīng)該左右兩邊有這相同的空格. 更進(jìn)一步, 兩個冒號也要有一樣的空格, 除了: 參數(shù)缺失, 空格也不需要加上了.
# 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:
  • 在函數(shù)調(diào)用的開括號前加入空格:
# 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.
  • 不要嘗試給把空格掛在最后. 因為空格通常不可見, 它可能會導(dǎo)致歧義: 比如, 在\后跟一個空格和一個新行, \將不會被認(rèn)為是多行連接符. 一些編輯器不會保存它, 很多項目有提交前檢查來拒絕這種情形.
  • 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等, 布爾操作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.
  • 有著不同優(yōu)先級的操作符被使用, 在最低優(yōu)先級的操作符左右加空格. 按你自己的標(biāo)準(zhǔn)來就行; 不要使用超過一個空格, 而且操作符左右的空格數(shù)一樣.
# 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.
  • $參數(shù)賦值或設(shè)定默認(rèn)參數(shù)時候, =兩端不設(shè)空格.
# 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.)
  • 函數(shù)注釋遵循冒號左右空格的處理法則, ->左右要用空格(查看下面的Function Annotations).
# 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).
  • 如果在函數(shù)注釋里說明參數(shù)默認(rèn)值, =號左右要有空格
# 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同行接一個短的語句是可以的, 但多重判斷和處理為連續(xù)多行是不可取的.
# 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.

逗號置尾是可選項, 除非表示只有一個元素的tuple(Python2中, 逗號置尾是有語法含義的). 為了明晰, 建議為以下示例的第二條前后加上括號(冗余).

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

塊注釋一般有一或多個段落, 段落有一或多句, 每句以句號結(jié)尾.

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.

按照Strunk和White(的作品<The Elements of Style>)書寫英文.

?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開發(fā)者們: 請用英語來書寫注釋, 除非你們100%確信你們的代碼不會被不懂你們語言的人閱讀.

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

塊注釋一般適用于一些(或全部)它后面的代碼, 每行以#開頭(除非注釋內(nèi)文本有縮進(jìn)).

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

塊注釋內(nèi)的段落由一個#獨(dú)占一行分隔.

Inline Comments

Use inline comments sparingly.

保守使用行內(nèi)注釋

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.

$行內(nèi)注釋與代碼同行, 與代碼間至少隔兩個空格, 并以#開頭.

Inline comments are unnecessary and in fact distracting if they state the obvious.

如果行內(nèi)注釋提供的信息在代碼中顯而易見, 那它就是多余的, 只能造成干擾.

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

公開的模塊, 函數(shù), 類, 方法要有文檔注釋. 非公開的不必要, 但應(yīng)該有個注釋描述方法做什么用的. 注釋應(yīng)該出現(xiàn)在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描述了文檔注釋的慣用約定. 結(jié)束處的"""應(yīng)該自成一行.

"""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包的命名風(fēng)格有點混亂, 所以做不到完全一致的風(fēng)格. 現(xiàn)在有以下建議(新的模塊和包應(yīng)該遵循, 但已有的遵照自身內(nèi)部一致性):

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的命名遵循"命名反映用途, 而非實現(xiàn)"的原則.

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.

變量命名的風(fēng)格應(yīng)獨(dú)立于命名的含義.

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
# (or `CapWords`, or `CamelCase` -- so named because of the bumpy look of its letters [4]). 
# This is also sometimes known as StudlyCaps.
# Note: When using acronyms in CapWords, capitalize all the letters of the acronym. Thus HTTPServerError is better than HttpServerError.
# $縮寫要保證所有字符大寫.

mixedCase # (differs from CapitalizedWords by initial lowercase character!)

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

也有使用短前綴來表示相關(guān)的變量名, Python中不常用. 如: os.stat()返回元組的原來的元素名是類似于st_mode,st_size之類的(這是為了強(qiáng)調(diào)它們與POSIX的調(diào)用結(jié)構(gòu)的關(guān)聯(lián), 這能幫助開發(fā)者熟悉).

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模塊為它的公共函數(shù)命名使用了X的開頭, Python認(rèn)為這種風(fēng)格是不必要的, 因為調(diào)用屬性和方法前會寫明對象, 調(diào)用函數(shù)會寫明函數(shù)所屬的模塊.

In addition, the following special forms using leading or trailing underscores are recognized (these can generally be combined with any case convention):

此外, 以_開頭或結(jié)尾的命名風(fēng)格也是可以的.

# weak "internal use" indicator. E.g. from M import * does not import objects whose name starts with an underscore.
# $內(nèi)部使用, 當(dāng)你用 from M import * 語句導(dǎo)入時, 以_開頭的內(nèi)容不會被導(dǎo)入.
_single_leading_underscore

# used by convention to avoid conflicts with Python keyword, e.g.
# 以_結(jié)尾的命名通常用于避免與Python關(guān)鍵字沖突的情形.
single_trailing_underscore_

Tkinter.Toplevel(master, class_='ClassName')

# when naming a class attribute, invokes name mangling (inside class FooBar, __boo becomes _FooBar__boo; see below).
# 屬性
__double_leading_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__

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,O,I不要單獨(dú)用作變量名.

In some fonts, these characters are indistinguishable from the numerals one and zero. When tempted to use 'l', use 'L' instead.
有些字體下, 上述的這些字符可能會不容易被區(qū)分.

ASCII Compatibility

Identifiers used in the standard library must be ASCII compatible as described in the policy section of PEP 3131.

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.

模塊要短, 小寫的命名, 包也是, 但不建議在包的命名中使用_.

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

當(dāng)一個C語言或C++語言寫的拓展包有一個更高抽象層級的Python包, 這個C或C++包應(yīng)該以一個_開頭.

Class Names

Class names should normally use the CapWords convention.

$類名遵循首字母大寫風(fēng)格.

The naming convention for functions may be used instead in cases where the interface is documented and used primarily as a callable.

函數(shù)的命名根據(jù)接口的文檔調(diào)整.

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.

內(nèi)建變量命名有兩種慣用約定: 大多是小寫的一兩個單詞(沒有下劃線連接), 一些首字母大寫風(fēng)格用于常量和異常.

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介紹了類型變量的命名, 一般推薦短小的, 首字母大寫(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).

Exception的命名同類的命名規(guī)范, 如果是個Error, 則以Error結(jié)尾.

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.

全局變量命名同模塊內(nèi)方法命名規(guī)范一樣.

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

用作導(dǎo)入全部的模塊, 應(yīng)使用__all__的機(jī)制來防止導(dǎo)入全局變量, 或者使用_前綴來命名不想被導(dǎo)入的變量避免它被導(dǎo)入(這種命名法表示你標(biāo)志這些變量為非公開的模塊變量).

Function and variable names

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

函數(shù)命名是小寫單詞, 以_連接(如果多個單詞能提高可讀性的話).

Variable names follow the same convention as function names.

變量命名規(guī)范同函數(shù).

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

首字符小寫的命名風(fēng)格僅在為了兼容歷史代碼可以被接受.

Function and method arguments

Always use self for the first argument to instance methods.

實例方法的首個參數(shù)寫為self.

Always use cls for the first argument to class methods.

類方法的首個參數(shù)寫為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.)

如果函數(shù)參數(shù)名與Python關(guān)鍵字沖突, 建議添加_后綴, 而不是用縮寫或去除元音(如class寫為class_, 而不是clss, 最好還是避免沖突的情況).

Method Names and Instance Variables

Use the function naming rules: lowercase with words separated by underscores as necessary to improve readability.

方法和實例變量的命名和函數(shù)一樣.

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的命名修飾規(guī)則兼容.

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

關(guān)于這有些爭論, 下面會提到.

Constants

Constants are usually defined on a module level and written in all capital letters with underscores separating words. Examples include MAX_OVERFLOW and TOTAL.

$常量通常是模塊級別的, 寫法如: MAX_OVERFLOW,TOTAL.

Designing for inheritance

Always decide whether a class's methods and instance variables (collectively: "attributes") should be public or non-public. If in doubt, choose non-public; it's easier to make it public later than to make a public attribute non-public.

Public attributes are those that you expect unrelated clients of your class to use, with your commitment to avoid backward incompatible changes. Non-public attributes are those that are not intended to be used by third parties; you make no guarantees that non-public attributes won't change or even be removed.

We don't use the term "private" here, since no attribute is really private in Python (without a generally unnecessary amount of work).

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.

With this in mind, here are the Pythonic guidelines:

Public attributes should have no leading underscores.

考慮好你的類的屬性是公開的還是非公開的, 如果不確定, 先寫成非公開的, 方便以后改, 公開屬性不應(yīng)該以_開頭.

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

Note 1: See the argument name recommendation above for class methods.

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.

Note 1: Properties only work on new-style classes.

Note 2: Try to keep the functional behavior side-effect free, although side-effects such as caching are generally fine.

以上不翻了.

Note 3: Avoid using properties for computationally expensive operations; the attribute notation makes the caller believe that access is (relatively) cheap.

$屬性不應(yīng)該是那種需要大量計算的內(nèi)容.

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.

如果你設(shè)計的父類會派生子類, 有些方法不想讓子類繼承, 可以以__開頭, 不以_結(jié)尾的風(fēng)格命名它們, 這會觸發(fā)Python的名稱修飾機(jī)制.

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.

Note 3: Not everyone likes name mangling. Try to balance the need to avoid accidental name clashes with potential use by advanced callers.

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.

只對公開接口保證向前兼容性, 相應(yīng)的, 讓用戶能夠清楚的區(qū)分公開和內(nèi)部接口.

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.

寫于文檔的接口應(yīng)該是被認(rèn)為公開的, 除非特別聲明, 所有沒有列在文檔上的接口應(yīng)該被認(rèn)為是內(nèi)部的.

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.

模塊的所有公開接口應(yīng)在__all__里聲明, 如果__all__是空列表, 說明該模塊沒有公開接口.

Even with all set appropriately, internal interfaces (packages, modules, classes, functions, attributes or other names) should still be prefixed with a single leading underscore.

內(nèi)部接口應(yīng)該以_開頭.

An interface is also considered internal if any containing namespace (package, module or class) is considered internal.

如果使用了內(nèi)部的命名空間, 這個接口應(yīng)該也是內(nèi)部的.

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.

除非是文檔明確說明的公開接口, 模塊不能依賴導(dǎo)入的名稱.

Programming Recommendations

  • Code should be written in a way that does not disadvantage other implementations of Python (PyPy, Jython, IronPython, Cython, Psyco, and such).

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.

  • 采用一種不會因為其他的Python實現(xiàn)方式而產(chǎn)生不利的寫法.
    如用CPython的這種拼接字符的高效寫法a += ba = a + b, 在其他的Python實現(xiàn)并不一定高效. 建議使用''.join(), 它以線性時間復(fù)雜度實現(xiàn)字符拼接.
  • Comparisons to singletons like None should always be done with is or is not, never the equality operators.
  • $對None進(jìn)行比較, 要用is, is not.

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!

  • 當(dāng)在用if x表達(dá)if x is None時候, 一定要有清楚的認(rèn)識, 就是x的類型的某些實例可能在布爾語境下為false.
  • Use is not operator rather than not ... is. While both expressions are functionally identical, the former is more readable and preferred.
  • $用is not而不是not is.
# 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.

To minimize the effort involved, the functools.total_ordering() decorator provides a tool to generate missing comparison methods.

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.

  • $當(dāng)要實現(xiàn)一個可比較類時候, 建議實現(xiàn)這六個__eq__,__ne__, __lt__, __le__, __gt__, __ge__方法.
    為了減小工作量, functools.total_ordering()裝飾器可以幫忙實現(xiàn).
    PEP 207說明了Python中, 自反性是默認(rèn)滿足的, 所以建議完全實現(xiàn)以上六個方法.
  • Always use a def statement instead of an assignment statement that binds a lambda expression directly to an identifier.
# 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)

  • def來聲明函數(shù), 而不是將匿名函數(shù)命名.
    示例中, 第一個更易錯誤回溯和表達(dá).

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

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)

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.

  • $從Exception而不是BaseException繼承.
  • Use exception chaining appropriately. In Python 3, "raise X from Y" should be used to indicate explicit replacement without losing the original 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).

  • 適當(dāng)?shù)氖褂卯惓f?
  • When raising an exception in Python 2, use raise ValueError('message') instead of the older form raise ValueError, 'message'.

The latter form is not legal Python 3 syntax.

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.

  • Python 2中, 用raise ValueError('msg')而不是老的寫法raise ValueError 'msg', 后一種在Python 3中是不合法的.
  • When catching exceptions, mention specific exceptions whenever possible instead of using a bare except: clause.
# For example, use:
try:
    import platform_specific_module
except ImportError:
    platform_specific_module = None

A bare except: clause will catch SystemExit and KeyboardInterrupt exceptions, making it harder to interrupt a program with Control-C, and can disguise other problems. If you want to catch all exceptions that signal program errors, use except Exception: (bare except is equivalent to except BaseException:).

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

  1. If the exception handler will be printing out or logging the traceback; at least the user will be aware that an error has occurred.
  2. 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.
  • $except:語句要指定盡量特定的異常類型, 如果想要捕獲全部異常, 用except exception:.
  • When binding caught exceptions to a name, prefer the explicit name binding syntax added in 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.

  • 將捕獲的異常命名, 用如示例的寫法.
  • When catching operating system errors, prefer the explicit exception hierarchy introduced in Python 3.3 over introspection of errno values.
  • 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.

  • 上下文管理器應(yīng)該被獨(dú)立調(diào)用, 而不僅僅是用作獲取和釋放資源.
    后一個例子就沒有提供任何__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).
# 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)
  • $函數(shù)中的return要有一致性, 若某出寫了return, 那就應(yīng)該在函數(shù)其他出口處明確寫return None
  • 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.

  • 使用string方法而不是string模塊.
  • Use ''.startswith() and ''.endswith() instead of string slicing to check for prefixes or suffixes.

startswith() and endswith() are cleaner and less error prone. For example:

# Yes:
if foo.startswith('bar'):
# No:
if foo[:3] == 'bar':
  • $使用''.startswith()''.endswith()而不是字符串切片來檢查字符串前后綴.
  • Object type comparisons should always use isinstance() instead of comparing types directly.
# 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:

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)

  • $類型比較使用isinstance()而不是直接比較類型.
    注意Python 2中的strunicode, 它們共有父類是basestring.
    注意Python 3中, unicodebasestring不復(fù)存在, bytes也不認(rèn)為是字符串的一種.
  • 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):
  • 空串的布爾值為false.
  • 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.
  • 不要在字符串末尾留下多個空格.
  • Don't compare boolean values to True or False using ==.
# 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被采納后, 函數(shù)注釋的風(fēng)格也發(fā)生變化(參考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.)
  • 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.
  • 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].
  • 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].

Variable annotations

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

  • 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
  • Although the PEP 526 is accepted for Python 3.6, the variable annotation syntax is the preferred syntax for stub files on all versions of Python (see PEP 484 for details).
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容