PEP8中文翻譯(轉)


原文:https://github.com/zgia/manual

PEP 8 -- Style Guide for Python Code

skip to navigation
skip to content
PEP: 8
Title: Style Guide for Python Code
Version: dc5a21b8bc47
Last-Modified: 2012-03-15 08:24:13 +0100 (Thu, 15 Mar 2012)
Author: Guido van Rossum <guido at python.org>, Barry Warsaw <barry at python.org>
Status: Active
Type: Process
Content-Type: text/x-rst
Created: 05-Jul-2001
Post-History: 05-Jul-2001
翻譯: zgia, albert

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代碼的。Python的C語言實現的C代碼風格指南,請參閱PEP 7[1]

This document was adapted from Guido's original Python Style Guide essay [2], with some additions from Barry's style guide [3]. Where there's conflict, Guido's style rules for the purposes of this PEP. This PEP may still be incomplete (in fact, it may never be finished <wink>).

這篇文檔改編自Guido(譯者注:Python之父,Guido van Rossum)最初的《Python Style Guide》[2]一文,《Barry's style guide》[3]亦有貢獻。對(2文)有沖突的地方,Guido的風格指南更符合這份PEP思想。當然,這份PEP仍不完善(實際上,它可能永遠也無法完善<wink>)

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 所表述的,“可讀性很重要”。(譯者注:可以點擊這里查看由lanphaday翻譯的“The Zen of Python”。)

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 most important.

這是一份關於一致性的風格指南。這份風格指南的風格一致性是非常重要的。更重要的是項目的風格一致性。在一個模塊或函數的風格一致性是最重要的。

But most importantly: know when to be inconsistent -- sometimes the style guide just doesn't apply. When in doubt, use your best judgment. Look at other examples and decide what looks best. And don't hesitate to ask!

但最重要的是:知道什么時候是不一致的————有時風格指南並不適用。有疑問時,請使用您的最佳判斷。看看其他的例子,並決定什么看上去最美觀。不要猶豫,提示提問!

Two good reasons to break a particular rule:

兩個很好的理由來打破特定規則:

  1. When applying the rule would make the code less readable, even for someone who is used to reading code that follows the rules.

    應用了這個規則后,代碼的可讀性卻降低了。甚至有人依據以下的規則來閱讀代碼。

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

    欲與周圍的代碼的代碼保持一致,也會打破這個規則(也許是歷史的原因)————雖然這也是一個機會來收拾別人的爛攤子(真正的XP風格)。(譯者注:XP,Xtreme Programming,極限編程)

Code lay-out 代碼布局

Indentation 縮進和換行

Use 4 spaces per indentation level.

每級縮進使用 4 個空格。

For really old code that you don't want to mess up, you can continue to use 8-space tabs.

如果不想搞亂以前的古老的代碼的話,可以使用8個空格長的制表符。

Continuation lines should align wrapped elements either vertically using Python's implicit line joining inside parentheses, brackets and braces, or using a hanging indent. When using a hanging indent the following considerations should be applied; there should be no arguments on the first line and further indentation should be used to clearly distinguish itself as a continuation line.

續行應該與其包裹元素對齊,要么使用圓括號、方括號和花括號內的隱式行連接來垂直對齊;要么使用懸掛式縮進對齊。使用懸掛式縮進時,應該考慮下面的意見。第一行不應該有參數;使用縮進以便與其他代碼區分清楚。

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)

No:

# Arguments on first line forbidden when not using vertical alignment
# 沒有使用垂直對齊時,禁止把參數放在第一行
foo = long_function_name(var_one, var_two,
    var_three, var_four)

# Further indentation required as indentation is not distinguishable
# 縮進不夠,代碼不清晰
def long_function_name(
    var_one, var_two, var_three,
    var_four):
    print(var_one)

Optional:

可選:

# Extra indentation is not necessary.
foo = long_function_name(
  var_one, var_two,
  var_three, var_four)

Tabs or Spaces? 制表符或者空格?

Never mix tabs and spaces.

絕不要混用制表符和空格。

The most popular way of indenting Python is with spaces only. The second-most popular way is with tabs only. Code indented with a mixture of tabs and spaces should be converted to using spaces exclusively. When invoking the Python 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!

最流行的 Python 縮進方式是僅使用空格,其次是僅使用制表符。混合着制表符和空格縮進的代碼將被轉換成僅使用空格。使用帶-t選項來調用Python命令行解釋器時,代碼中非法混用制表符和空格會給出警告。當使用-tt選項時這些警告就會變成錯誤。高度建議使用這些選項。

For new projects, spaces-only are strongly recommended over tabs. Most editors have features that make this easy to do.

對新的項目,強烈建議只使用空格而不是制表符。大多數的編輯器都能輕松做到這一點。

Maximum Line Length 行的最大長度

Limit all lines to a maximum of 79 characters.

限制所有行的最大長度為 79 個字符。

There are still many devices around that are limited to 80 character lines; plus, limiting windows to 80 characters makes it possible to have several windows side-by-side. The default wrapping on such devices disrupts the visual structure of the code, making it more difficult to understand. Therefore, please limit all lines to a maximum of 79 characters. For flowing long blocks of text (docstrings or comments), limiting the length to 72 characters is recommended.

周圍還有很多設備限制每行 80個字符。而且,限制窗口顯示 80 個字符可以並排顯示多個窗口。有些設備上,默認折行會打亂代碼結構,不易理解。因此,請限制所有行的最大長度為 79 個字符。對一大段長文本(文檔字符串或注釋),推薦限制每行最多72個字符。

The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces. Long lines can be broken over multiple lines by wrapping expressions in parentheses. These should be used in preference to using a backslash for line continuation. Make sure to indent the continued line appropriately. The preferred place to break around a binary operator is after the operator, not before it. Some examples:

較長代碼行折行的首選方法是在圓括號、方括號和花括號內使用Python的隱式續行方式。通過圓括號內的表達式的折行來把較長的代碼行折成多行。這種方式要優先使用,優先於反斜杠。同時確保適當的續行縮進。二元運算符的首選的折行處是在運算符之后,而不是之前。請看一些例子:

class Rectangle(Blob):

    def __init__(self, width, height,
                 color='black', emphasis=None, highlight=0):
        if (width == 0 and height == 0 and
            color == 'red' and emphasis == 'strong' or
            highlight > 100):
            raise ValueError("sorry, you lose")
        if width == 0 and height == 0 and (color == 'red' or
                                           emphasis is None):
            raise ValueError("I don't think so -- values are %s, %s" %
                             (width, height))
        Blob.__init__(self, width, height,
                      color, emphasis, highlight)

Blank Lines 空行

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

頂層函數和類之間使用兩個空行。

Method definitions inside a class are separated 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).

(謹慎地)使用額外的空白行來分隔一組相關的函數。一堆相關的單行代碼之間的空白行可以省略(例如,一組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的代碼閱讀器可能無法識別control-L為換頁,將在其位置顯示另一個字形。

Encodings (PEP 263) 編碼

Code in the core Python distribution should always use the ASCII or Latin-1 encoding (a.k.a. ISO-8859-1). For Python 3.0 and beyond, UTF-8 is preferred over Latin-1, see PEP 3120.

Python核心發行代碼應該總是使用 ASCII 或 Latin-1 編碼 (又名 ISO-8859-1)。Python 3.0 和以后的版本,首選 UTF-8 而不是 Latin-1,請查看 PEP 3120 獲取更多信息。(譯者注:對中文項目,請首選UTF-8。)

ASCII 編碼的文件不應該有coding cookie(譯者注:# -*- coding: utf-8 -*-,# coding=utf-8)。Latin-1(或 UTF-8 )只應該當注釋或文檔字符串涉及作者名需要 Latin-1 時才使用;否則,使用 \x\u\U等轉義字符是在字符串中包含非 ASCII 數據的首選方法。

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 MUST provide a latin transliteration of their names.

對Python 3.0 和以后的版本來說,下述政策僅對標准庫作出限制(請查閱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 MUST provide a latin transliteration of their names.

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

面向全球用戶的開源項目,鼓勵采用類似的政策。

Imports 導入

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

    導入通常應當使用單獨的行,例如:

    Yes: import os
         import sys
    
    No:  import sys, os
    

    It's okay to say this though:

    但是可以這么做:

    from subprocess import Popen, PIPE
    
  • Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants.

    導入總是位於文件的頂部,在模塊注釋和文檔字符串之后,在模塊的全局變量與常量之前。

    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.

    每組導入之間使用空行隔開。

    Put any relevant __all__ specification after the imports.

    在導入之后放置任何相關的 __all__ 說明書。

  • Relative imports for intra-package imports are highly discouraged. Always use the absolute package path for all imports. Even now that PEP 328 is fully implemented in Python 2.5, its style of explicit relative imports is actively discouraged; absolute imports are more portable and usually more readable.

    非常不推薦在包內導入中使用相對路徑導入。對所有導入來說,總是使用絕對包路徑導入。盡管PEP 328 在Python 2.5中已經完全實現,但是相對路徑導入一直以來都是不推薦的,絕對路徑導入更容易移植,而且常常更容易閱讀。

  • 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

    如果上述寫法導致內部名稱沖突,那么可以這么寫:

    import myclass
    import foo.bar.yourclass
    

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

    分別這樣使用:"myclass.MyClass" 和 "foo.bar.yourclass.YourClass"。

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 } )
    
  • 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
    
  • 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: dict['key'] = list[index]
    No:  dict ['key'] = list [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 其他建議

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

    總是在這些二元運算符前后加一個空格:賦值(=),自增賦值(+=-= 等等), 比較(==<>!=<><=>=innot inisis not),布爾運算(andornot)。

  • Use spaces around arithmetic operators:

    在算術運算符前后加空格:

    Yes:

    i = i + 1
    submitted += 1
    x = x * 2 - 1
    hypot2 = x * x + y * y
    c = (a + b) * (a - b)
    

    No:

    i=i+1
    submitted +=1
    x = x*2 - 1
    hypot2 = x*x + y*y
    c = (a+b) * (a-b)
    
  • Don't use spaces around the = sign when used to indicate a keyword argument or a default parameter value.

    不要在一個關鍵字參數或者一個缺省參數值的 = 符號前后加一個空格。

    Yes:

    def complex(real, imag=0.0):
        return magic(r=real, i=imag)
    

    No:

    def complex(real, imag = 0.0):
        return magic(r = real, i = imag)
    
  • 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()
    

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. If a comment is a phrase or sentence, its first word should be capitalized, unless it is an identifier that begins with a lower case letter (never alter the case of identifiers!).

注釋應該是一條完整的句子。如果注釋是一個短語或句子,它的第一個字應該大寫,除非它是一個小寫字母開頭的標識符(絕對不要改變標識符的大小寫)。

If a comment is short, the period at the end can be omitted. Block comments generally consist of one or more paragraphs built out of complete sentences, and each sentence should end in a period.

如果注釋很短,那么結尾的句號可以省略。塊注釋通常由一個或多個段落組成, 這些段落由完整的句子構成,每個句子都應該使用句號結尾。

You should use two spaces after a sentence-ending period.

句號結尾的句子后面應該有2個空格。

When writing English, Strunk and White apply.

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.

內嵌注釋是一種和語句在同一行的注釋。內嵌注釋至少和語句間隔2個空格。他們開始於一個 # 和一個空格。

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.

編寫良好的文檔字符串(documentation strings,又名 "docstrings")的約定永生(:()在 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.

    所有的公告模塊,函數,類和方法都需要編寫文檔字符串。對非公共的方法而言,文檔字符串則不是必要的,但是可以使用一個注釋來描述這個方法。這個注釋必須位於 def 行之后。

  • PEP 257 describes good docstring conventions. Note that most importantly, the """ that ends a multiline docstring should be on a line by itself, and preferably preceded by a blank line, e.g.:

    PEP 257 描述了一個良好的文檔字符串的編寫約定。注意最重要的是,""" 作為多行的文檔字符串的結束,應該單獨一行,例如:

    """Return a foobang
    
    Optional plotz says to frobnicate the bizbaz first.
    
    """
    
  • For one liner docstrings, it's okay to keep the closing """ on the same line.

    對單行的文檔字符串來說,結尾的 """ 在同一行。

Version Bookkeeping 版本注記

If you have to have Subversion, CVS, or RCS crud in your source file, do it as follows.

如果在代碼源文件中摻雜着Subversion,CVS或RCS注記,按照下面的規則書寫。

__version__ = "$Revision: dc5a21b8bc47 $"
# $Source$

These lines should be included after the module's docstring, before any other code, separated by a blank line above and below.

這些行在塊注釋之后,其他代碼之前。前后各有一個空行。

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庫的命名約定有點亂,所以我們從未達成完全一致。但是,目前有一些推薦的標准。 新的模塊和包(包括第三方框架)應該用這些標准,但是擁有不同風格的固有庫,還是保持內部統一更好。

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 (or CapWords, or CamelCase -- so named because of the bumpy look of its letters [4]). This is also sometimes known as StudlyCaps.

    CapitalizedWords (或 CapWords,或 CamelCase -- 這樣命名因為其字母有起伏的外觀[4])。這有時也被稱為 StudlyCaps。

    Note: When using abbreviations in CapWords, capitalize all the letters of the abbreviation. Thus HTTPServerError is better than HttpServerError.

    注意:當首字大寫中用到縮寫時,所有字符用大寫。因此HTTPSeverError比HttpSeverError好。

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

    mixedCase(不同於首字符大寫,開始是小寫字母!)

  • Capitalized_Words_With_Underscores (ugly!)(丑陋之極!)

There's also the style of using a short unique prefix to group related names together. This is not used much in Python, but it is mentioned for completeness. For example, the os.stat() function returns a tuple whose items traditionally have names like st_mode, st_size, st_mtime and so on. (This is done to emphasize the correspondence with the fields of the POSIX system call struct, which helps programmers familiar with that.)

也有用唯一短前綴來組織相關字符的方法。在Python中用的不多。但為了完整提一下。比如,os.stat()返回一個元組, 里面的條目是傳統的名字,如st_mode, st_size, st_mtime 等。 (這么做是為了與 POSIX 系統的調用一致,以幫助程序員熟悉它。)

The X11 library uses a leading X for all its public functions. In Python, this style is generally deemed unnecessary because attribute and method names are prefixed with an object, and function names are prefixed with a module name.

X11庫的所有公共函數用了前導X。在Python中,這種風格通常被視為非必須的,因為屬性和方法的名字用類做前綴,方法名用模塊名做前綴。

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

另外,下面用前導和結尾下划線的特殊格式是被認可的(通常和一些示例規范結合)

  • _single_leading_underscore: weak "internal use" indicator. E.g. from M import * does not import objects whose name starts with an underscore.

    _single_leading_underscore:(單下划線開始)弱"內部使用"指示器。例如:from M import * 不會導入以下划線開始的對象。

  • single_trailing_underscore_: used by convention to avoid conflicts with Python keyword, e.g.

    single_trailing_underscore_:(單下划線結束)規定使用其來避免與Python關鍵字沖突,例如:

    Tkinter.Toplevel(master, class_='ClassName')
    
  • __double_leading_underscore: when naming a class attribute, invokes name mangling (inside class FooBar, __boo becomes _FooBar__boo; see below).

    __double_leading_underscore:(雙下划線開始)命名一個類的屬性時,調用"名字變化"(類FooBar中,__boo 變為了 _FooBar__boo; 見下文)。

  • __double_leading_and_trailing_underscore__: "magic" objects or attributes that live in user-controlled namespaces. E.g. __init__, __import__ or __file__. Never invent such names; only use them as documented.

    __double_leading_and_trailing_underscore__:(雙下划線開始和結束)"magic"對象或屬性存活於用戶控制的命名空間。 例如__init__, __import____file__。永遠不要起這樣的名字;只在文檔中使用。

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.

在某些字體中,這些字很難和數字的0 和 1 區分。當打算用'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的包也要用全小寫的,短名稱,但是不建議用下划線。

Since module names are mapped to file names, and some file systems are case insensitive and truncate long names, it is important that module names be chosen to be fairly short -- this won't be a problem on Unix, but it may be a problem when the code is transported to older Mac or Windows versions, or DOS.

因為模塊名稱和文件名關聯,而且某些文件系統大小寫不敏感,也會截斷過長的名字。所以模塊選用相當簡短的名字是很重要的。 在Unix下不會有這樣的問題,但是在早些的Mac、Windows 或者 DOS下會有這樣的問題。

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 類名

Almost without exception, class names use the CapWords convention. Classes for internal use have a leading underscore in addition.

毫無例外,類名要用首字母大寫的規則。內部類,要加上前導下划線。

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

被設計為通過from M import *導入的模塊。應該用__all__機制來防止導出全局。 或者使用過去的全局變量前置下划線的規則(這是為了說明這些變量是"模塊私有的")。

Function Names 函數名

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

函數名應該用小寫,為了增加可讀性可以用下划線分隔。

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

大小寫混合僅在為了兼容原有大小寫混合風格占主體的情況下使用(比如 threading.py)。

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.

始終用cls作為類方法的第一個參數。

If a function argument's name clashes with a reserved keyword, it is generally better to append a single trailing underscore rather than use an abbreviation or spelling corruption. Thus class_ is better than clss. (Perhaps better is to avoid such clashes by using a synonym.)

如果函數的參數名和保留字沖突。用結尾下划線比縮寫或是濫用的組詞更好。因此 class_clss好。(也許,更好的避免沖突的方式是用同義詞。)

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.__a讀取。 (執着的用戶還是可以用Foo._Foo__a.讀取。)

Note: there is some controversy about the use of __names (see below).

注意:關於__names的使用有一些爭論(見下文)。

Constants 常量

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

常量通常在模塊級別中定義,用全大寫和下划線分隔的字符來編寫。例如MAX_OVERFLOWTOTAL

Designing for inheritance 繼承設計

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

總要考慮一個類的方法或實例變量(總體而言:屬性)應該是公用的或者非公用的。如果不能確定的話,設計為私有的。 因為,之后將一個私有的改為公有的要比將公有的變為私有的容易。

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

公有屬性,是你希望與這個類無關的客戶使用的,並通過你的委托機制來避免由於屬性變更導致的向后不兼容。 私有屬性,是你不希望被第三方使用的。你不能保證私有屬性不會改變甚至被刪除。

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

在這里我們沒有使用術語"private",因為在Python並沒有真正的私有屬性(為了避免大量不必要的常規工作)

Another category of attributes are those that are part of the "subclass API" (often called "protected" in other languages). Some classes are designed to be inherited from, either to extend or modify aspects of the class's behavior. When designing such a class, take care to make explicit decisions about which attributes are public, which are part of the subclass API, and which are truly only to be used by your base class.

另一種屬性,是"subclass API" 的一部分(通常,在某些語言里被稱作"protected")。有一些類設計的時候是用來繼承的。 用於擴展或者改變類的自身行為的某些方面。當設計這樣的類的時候,一定要弄清楚哪些屬性是公有的,哪些是subclass API的子集,哪些是真正只在自己的基類中使用的

With this in mind, here are the Pythonic guidelines:

貫穿着這樣的思想,如下是Python的准則:

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

    對於單一的公有數據屬性,最好是直接用其屬性名,而非復雜的存取器/突變期方法。 需要記得的是,Python為今后由簡單的數據屬性擴充為方法操作提供了簡單的途徑。 因此,運用屬性來實現簡單數據存取語法對於方法實現的透明化處理。

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

    注意1:屬性只在new-style 類中起作用

    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.

    屬性標記讓調用者認為存取開銷(相當的)小。所以,避免用屬性進行開銷昂貴的操作。

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

    注意1:要注意的是只有簡單類名(simple class name)才能在名稱錯位中使用。 所以,如果一個子類同時用相同的類名和屬性名,還是會造成名稱沖突。

    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.

    "名稱變化術"可用作某些用途,比如調試,__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:並不是所有人喜歡"名稱變化術"。嘗試平衡需求,避免由於之前潛在的調用造成的意外的名稱沖突。

Programming Recommendations  程序設計建議

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

    代碼應該用不損害其他Python實現的方式去編寫(PyPy, Jython, IronPython, Cython, Psyco 等)

    For example, do not rely on CPython's efficient implementation of in-place string concatenation for statements in the form a += b or a = a + b. Those statements run more slowly in Jython. In performance sensitive parts of the library, the ''.join() form should be used instead. This will ensure that concatenation occurs in linear time across various implementations.

    例如,不要依賴於CPython的高效內置字符連接語句a += b or a = a + b.這些語句在Jython中運行較慢。在性能敏感的庫中,應該用''.join() 來取代。這樣可以保證在不同的實現中,字符鏈接花費的時間都呈線性。

  • Comparisons to singletons like None should always be done with is or is not, never the equality operators.

    Also, beware of writing if x when you really mean if x is not None -- e.g. when testing whether a variable or argument that defaults to None was set to some other value. The other value might have a type (such as a container) that could be false in a boolean context!

    與諸如None這樣的字符比較時,要使用is or is not,永遠不要用等於操作。

    同樣地,在測試一個變量或參數默認值為None被設置為其他值時(比如if x表示if x is not None時),要注意。 這個值應該有一個能在布爾邏輯的上下文中為false的類型(比如容器)。

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

    當用復雜比較實現排序操作時,最好去實現全部六個操作(__eq__, __ne__, __lt__, __le__, __gt__, __ge__),而不是依靠其他的代碼去實現一些怪異的比較。

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

    為了最大程度的減少實現這一過程的開銷。functools.total_ordering()提供了生成缺少的比較操作的方法。

    PEP 207 indicates that reflexivity rules are assumed by Python. Thus, the interpreter may swap y > x with x < y, y >= x with x <= y, and may swap the arguments of x == y and x != y. The sort() and min() operations are guaranteed to use the < operator and the max() function uses the > operator. However, it is best to implement all six operations so that confusion doesn't arise in other contexts.

    PEP 207指出Python實現了反射。因此,解釋器會將y > x 轉換為 x < y, y >= x轉換為 x <= y,也會轉換x == yx != y的參數.The sort()min()被確保使用<操作符,max()使用>操作符。 但是,最好實現全部六個操作,以避免在其他地方造成的沖突。

  • Use class-based exceptions.

    使用基於對象的異常

    String exceptions in new code are forbidden, because this language feature is being removed in Python 2.6.

    字符異常在新的代碼中被禁止了,因為這一語言特性在2.6版本中被移除了。

    Modules or packages should define their own domain-specific base exception class, which should be subclassed from the built-in Exception class. Always include a class docstring. E.g.:

    模塊或者包應該定義自己的異常基類,這個類應該繼承自內置的Exception類。總要包含類文檔語句,例如:

    class MessageError(Exception):
        """Base class for errors in the email package."""
    

    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 need no special suffix.

    在這里用到類命名規范。盡管當你的“異常”是一個“錯誤”(error)時,你應該在自己的異常類加上后綴"Error"。 非錯誤類(Non-error)異常,不需要特別的后綴。

  • When raising an exception, use raise ValueError('message') instead of the older form raise ValueError, 'message'.

    當拋出一個異常的時候,使用raise ValueError('message')代替舊的raise ValueError, 'message'格式。

    The paren-using form is preferred because when the exception arguments are long or include string formatting, you don't need to use line continuation characters thanks to the containing parentheses. The older form will be removed in Python 3.

    推薦使用這種括弧的格式,當異常的參數很長或者是格式化字符串的時候,由於括號的關系,我們不需要使用連字符。 舊的格式在Python 3 中被移除。

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

    當捕獲一個異常的時候,要用詳細異常聲明代替光禿禿的except: 語句.

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

    一個空的except:語句將會捕獲 SystemExit 和 KeyboardInterrrupt 異常。這會使得很難用Control-C來中斷一個程序,並且還會隱藏其他的問題。 如果你想捕獲一個程序中的所有異常,使用except Exception: (bare 和except BaseException:是等價的)。

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

    經驗告訴我們在兩個情況下避免使用空‘except’

    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.

      如果代碼要做一些收尾工作,但是隨后要用 raise向上拋出異常。try...finally可以更好地處理這個問題。

  • 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)
    
  • Use string methods instead of the string module.

    使用String方法而非String模塊

    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方法更加快捷並且使用和unicode字符一樣的API。如果需要向后兼容2.0之前的版本的話,可以不考慮這條規則。

  • Use ''.startswith() and ''.endswith() instead of string slicing to check for prefixes or suffixes.

    使用''.startswith()''.endswith()而非字符切片去檢測前綴或后綴。

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

    startswith() and endswith() 更加綠色,錯誤更少。例如:

    Yes: if foo.startswith('bar'):
    No:  if foo[:3] == 'bar':
    

    The exception is if your code must work with Python 1.5.2 (but let's hope not!).

    例外的就是如果你的代碼必須在Python 1.5.2運行(但是,假設它不是)。

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

    對象類型比較總要用 isinstance() 而非直接比較

    Yes: if isinstance(obj, int):
    
    No:  if type(obj) is type(1):
    

    When checking if an object is a string, keep in mind that it might be a unicode string too! In Python 2.3, str and unicode have a common base class, basestring, so you can do:

    當檢測一個對象是否是字符串是,記住,它可能是unicode字符。在Python 2.3, str和unicode有同樣的基類——basestring, 那么你可以這樣做:

    if isinstance(obj, basestring):
    
  • For sequences, (strings, lists, tuples), use the fact that empty sequences are false.

    對於序列,(strings, lists, tuples),利用空序列為false這一點。

    Yes: if not seq:
         if seq:
    
    No: if len(seq)
        if not len(seq)
    
  • Don't write string literals that rely on significant trailing whitespace. Such trailing whitespace is visually indistinguishable and some editors (or more recently, reindent.py) will trim them.

    書寫字面值時不要依靠后面的空格。這些后面的空格,視覺上難以區分,而且很多編輯器(或者,眼前的,reindent.py)會去掉他們。

  • Don't compare boolean values to True or False using ==.

    別用‘==’進行布爾值和 True 或者 False 的比較

    Yes:   if greeting:
    No:    if greeting == True:
    Worse: if greeting is True:
    

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM