一致性1

一致性很重要,但盲目追求一致更加愚不可及。

布局2

语句3

通常每条语句独占一行

正例:

if foo == 'blah':
    do_blah_thing()
do_one()
do_two()
do_three()

反例:

if foo == 'blah': do_blah_thing()
do_one(); do_two(); do_three()

缩进4

使用 4 个空格5进行缩进

行宽6

分号10

圆括号11

正例:

if foo:
    bar()
while x:
    x = bar()
if x and y:
    bar()
if not x:
    bar()
return foo
for (x, y) in dict.items(): ...

反例:

if (x):
    bar()
if not(x):
    bar()
return (foo)

拖尾逗号(trailing comma)12

空行13

空格15

Shebang16

根据 PEP-394,程序的 main 文件应该以 #!/usr/bin/python2#!/usr/bin/python3 开始。

编码17

模块文件的头部包含UTF-8编码声明

# -*- coding: utf-8 -*-

导入18

模块级元数据20

比如:

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

字符串21

注释22

使用注释块还是行内注释23

# We use a weighted dictionary search to find out where i is in
# the array.  We extrapolate position based on the largest num
# in the array and the array size and then do binary search to
# get the exact number.

if i & (i-1) == 0:        # true iff i is a power of 2

注释块24

行内注释25

TODO注释26

文档字符串27

函数和方法以及生成器23

文档字符串是必需的,除非:

关于函数的各方面应在特定的小节中进行描述记录,每节应该以一个标题行开始,标题行以冒号结尾。 除标题行外,小节的其他内容应缩进两空格。若该函数为装饰器,则文档中应明确说明28

例如:

def fetch_bigtable_rows(big_table, keys, other_silly_variable=None):
    """Fetches rows from a Bigtable.

    Retrieves rows pertaining to the given keys from the Table instance
    represented by big_table.  Silly things may happen if
    other_silly_variable is not None.

    Args:
        big_table: An open Bigtable Table instance.
        keys: A sequence of strings representing the key of each table row
            to fetch.
        other_silly_variable: Another optional variable, that has a much
            longer name than the other args, and which does nothing.

    Returns:
        A dict mapping keys to the corresponding table row data
        fetched. Each row is represented as a tuple of strings. For
        example:

        {'Serak': ('Rigel VII', 'Preparer'),
         'Zim': ('Irk', 'Invader'),
         'Lrrr': ('Omicron Persei 8', 'Emperor')}

        If a key from the keys argument is missing from the dictionary,
        then that row was not found in the table.

    Raises:
        IOError: An error occurred accessing the bigtable.Table object.
    """
    pass

23

类应该在其定义下有一段描述该类的文档字符串。 如果类有公共属性,那么文档中应该有一个描述属性的小节,并且遵循函数参数文档的格式。

例如:

class SampleClass(object):
    """Summary of class here.

    Longer class information....
    Longer class information....

    Attributes:
        likes_spam: A boolean indicating if we like SPAM or not.
        eggs: An integer count of the eggs we have laid.
    """

    def __init__(self, likes_spam=False):
        """Inits SampleClass with blah."""
        self.likes_spam = likes_spam
        self.eggs = 0

    def public_method(self):
        """Performs operation blah."""

如果使用注释编写类属性的文档,在 # 符号后添加一个冒号 :29:

class User(object):
    #: the name of the user as unicode string
    name = Column(String)
    #: the sha1 hash of the password + inline salt
    pw_hash = Column(String)

命名30

覆盖原则31

作为API的命名应该遵循使用惯例而非实现惯例。

应该避免的名称32

惯例34

模块名和包名35

类名36

类名为首字母大写单词串(CapWords)

Type variable names37

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:

from typing import TypeVar

VT_co = TypeVar('VT_co', covariant=True)
KT_contra = TypeVar('KT_contra', contravariant=True)

异常名38

全局变量名39

函数名40

函数和方法的参数41

方法名和实例变量42

常量44

全大写命名,可包含下划线

总结33

Type Public Internal
Modules module_name _module_name
Packages package_name
Classes ClassName _ClassName
Exceptions ExceptionName
Functions function_name() _function_name()
Global/Class Constants GLOBAL_CONSTANT_NAME _GLOBAL_CONSTANT_NAME
Global/Class Variables global_var_name _global_var_name
Instance Variables instance_var_name _instance_var_name (protected) or __instance_var_name (private)
Method Names method_name() _method_name() (protected) or __method_name() (private)
Function/Method Parameters function_parameter_name
Local Variables local_var_name

  1. A Foolish Consistency is the Hobgoblin of Little Minds - PEP 8 [return]
  2. Code lay-out - PEP 8 [return]
  3. Other Recommendations - PEP 8 [return]
  4. Indentation - PEP 8 [return]
  5. Tabs or Spaces? - PEP 8 [return]
  6. Maximum Line Length - PEP 8 [return]
  7. Line length - Google Python Style Guide [return]
  8. Should a line break before or after a binary operator? - PEP 8 [return]
  9. General Layout - The Pocoo Style Guide [return]
  10. Semicolons - Google Python Style Guide [return]
  11. Parentheses - Google Python Style Guide [return]
  12. When to use trailing commas - PEP 8 [return]
  13. Blank Lines - PEP 8 [return]
  14. Blank Lines - Google Python Style Guide [return]
  15. Whitespace in Expressions and Statements - PEP 8 [return]
  16. Shebang Line - Google Python Style Guide [return]
  17. Source File Encoding - PEP 8 [return]
  18. Imports - PEP 8 [return]
  19. Imports - Google Python Style Guide [return]
  20. Module level dunder names - PEP 8 [return]
  21. String Quotes - PEP 8 [return]
  22. Comments - PEP 8 [return]
  23. Comments - Google Python Style Guide [return]
  24. Block Comments - PEP 8 [return]
  25. Inline Comments - PEP 8 [return]
  26. TODO Comments - Google Python Style Guide [return]
  27. Documentation Strings - PEP 8 [return]
  28. Function and Method Decorators - Google Python Style Guide [return]
  29. Comments - The Pocoo Style Guide [return]
  30. Naming Conventions - PEP 8 [return]
  31. Overriding Principle - PEP 8 [return]
  32. Names to Avoid - PEP 8 [return]
  33. Naming - Google Python Style Guide [return]
  34. Descriptive: Naming Styles - PEP 8 [return]
  35. Package and Module Names - PEP 8 [return]
  36. Class Names - PEP 8 [return]
  37. Type variable names - PEP 8 [return]
  38. Exception Names - PEP 8 [return]
  39. Global Variable Names - PEP 8 [return]
  40. Function Names - PEP 8 [return]
  41. Function and method arguments - PEP 8 [return]
  42. Method Names and Instance Variables - PEP 8 [return]
  43. Naming Conventions - The Pocoo Style Guide [return]
  44. Constants - PEP 8 [return]