现在的位置: 首页 > 综合 > 正文

python风格规范

2013年10月28日 ⁄ 综合 ⁄ 共 6406字 ⁄ 字号 评论关闭

Python规范概述

跟其他大多数语言不一样,Python官方网站给出了风格规范。

小提示
PEP全称是,Python Enhancement Proposals,Python官网上提供了PEP,开发者可以从中学习到各类问题的最佳实践

可能是官网推荐的原因,社区里Python代码的风格规范基本上是一致的,很少有其他风格的代码(历史原因除外)。
在该基础上Google给出了更详细、明确的风格说明,主体上是一致的,但是粒度更细。而且Python作者也在Google,所以这里直接引用Google风格规范的翻译版。

Python哲学

金喜备注
之前要求使用该Python风格规范时,经常会有人要求在细节上调整,比如允许在行尾加空格、允许单行import 多个模块。
这样做法是可以的,不会影响代码运行、甚至还能有看上去比较合理的理由,比如习惯加分号后切换到C++中时不会忘记分号。
所以,这里我把The Zen of Python给出来,可以先了解一下,推荐大家尽量写出Pythonic的代码。
>>> import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

分号

小提示
不要在行尾加分号, 也不要用分号将两条命令放在同一行

行长度

小提示
每行不超过80个字符

例外: 如果使用Python 2.4或更早的版本, 导入模块的行可能多于80个字符.

Python会将圆括号, 中括号和花括号中的行隐式的连接起来, 你可以利用这个特点. 如果需要, 你可以在表达式外围增加一对额外的圆括号.

Yes
foo_bar(self, width, height, color='black', design=None, x='foo',
        emphasis=None, highlight=0)

if (width == 0 and height == 0 and
    color == 'red' and emphasis == 'strong'):

如果一个文本字符串在一行放不下, 可以使用圆括号来实现隐式行连接:

Yes
x = ('This will build a very long long '
     'long long long long long long string')

注意上面例子中的元素缩进; 你可以在本文的缩进部分找到解释.

括号

小提示
宁缺毋滥的使用括号

除非是用于实现行连接, 否则不要在返回语句或条件语句中使用括号. 不过在元组两边使用括号是可以的.

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

缩进

小提示
用4个空格来缩进代码

绝对不要用tab, 也不要tab和空格混用. 对于行连接的情况, 你应该要么垂直对齐换行的元素(见 行长度 部分的示例), 或者使用4空格的悬挂式缩进(这时第一行不应该有参数):

Yes
# Aligned with opening delimiter
foo = long_function_name(var_one, var_two,
                         var_three, var_four)

# 4-space hanging indent; nothing on first line
foo = long_function_name(
    var_one, var_two, var_three,
    var_four)
No
# Stuff on first line forbidden
foo = long_function_name(var_one, var_two,
    var_three, var_four)

# 2-space hanging indent forbidden
foo = long_function_name(
  var_one, var_two, var_three,
  var_four)

空行

小提示
顶级定义之间空两行, 方法定义之间空一行

顶级定义之间空两行, 比如函数或者类定义. 方法定义, 类定义与第一个方法之间, 都应该空一行. 函数或方法中, 某些地方要是你觉得合适, 就空一行.

空格

小提示
按照标准的排版规范来使用标点两边的空格

括号内不要有空格.

Yes
spam(ham[1], {eggs: 2}, [])
No
spam( ham[ 1 ], { eggs: 2 }, [ ] )

不要在逗号, 分号, 冒号前面加空格, 但应该在它们后面加(除了在行尾).

Yes
spam(ham[1], {eggs: 2}, [])
No
spam( ham[ 1 ], { eggs: 2 }, [ ] )

不要在逗号, 分号, 冒号前面加空格, 但应该在它们后面加(除了在行尾).

Yes
if x == 4:
    print x, y
x, y = y, x
No
if x == 4 :
    print x , y
x , y = y , x

参数列表, 索引或切片的左括号前不应加空格.

Yes
spam(1)
No
spam (1)
Yes
dict['key'] = list[index]
No
dict ['key'] = list [index]

在二元操作符两边都加上一个空格, 比如赋值(=), 比较(==, <, >, !=, <>, <=, >=, in, not in, is, is not), 布尔(and, or, not). 至于算术操作符两边的空格该如何使用, 需要你自己好好判断. 不过两侧务必要保持一致.

Yes
x == 1
No
x<1

当’=’用于指示关键字参数或默认参数值时, 不要在其两侧使用空格.

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

不要用空格来垂直对齐多行间的标记, 因为这会成为维护的负担(适用于:, #, =等):

Yes
foo = 1000  # comment
long_name = 2  # comment that should not be aligned

dictionary = {
    "foo": 1,
    "long_name": 2,
    }
No
foo       = 1000  # comment
long_name = 2     # comment that should not be aligned

dictionary = {
    "foo"      : 1,
    "long_name": 2,
    }

Python解释器

小提示
每个模块都应该以#!/usr/bin/env python<version>开头

模块应该以一个构造行开始, 以指定执行这个程序用到的Python解释器:

#!/usr/bin/env python2.4

总是使用最特化的版本, 例如, 使用/usr/bin/python2.4, 而不是 /usr/bin/python2. 这样, 当升级到不同的Python版本时, 能轻松找到依赖关系, 同时也避免了使用时的迷惑. 例如, /usr/bin/python2是表示/usr/bin/python2.0.1还是/usr/bin/python2.3.0?

注释

小提示
确保对模块, 函数, 方法和行内注释使用正确的风格

文档字符串

Python有一种独一无二的的注释方式: 使用文档字符串. 文档字符串是包, 模块, 类或函数里的第一个语句. 这些字符串可以通过对象的_doc_成员被自动提取, 并且被pydoc所用. (你可以在你的模块上运行pydoc试一把, 看看它长什么样). 我们对文档字符串的惯例是使用三重双引号. 一个文档字符串应该这样组织: 首先是一行以句号, 问号或惊叹号结尾的概述. 接着是一个空行. 接着是文档字符串剩下的部分, 它应该与文档字符串的第一行的第一个引号对齐. 下面有更多文档字符串的格式化规范.

模块

每个文件应该包含下列项, 依次是:

  1. 版权声明(例如, Copyright 2012 Taobao Inc.)
  2. 一个许可样板. 根据项目使用的许可(例如, Apache 2.0, BSD, LGPL, GPL), 选择合适的样板
  3. 作者声明, 标识文件的原作者.

函数和方法

如果不是既显然又简短, 任何函数或方法都需要一个文档字符串. 而且, 任何外部可访问的函数或方法, 不管多短多简单, 都需要文档字符串. 文档字符串应该包含函数做什么, 以及输入和输出的详细描述. 通常, 不应该描述”怎么做”, 除非是一些复杂的算法. 对于技巧性的代码, 块注释或者行内注释是最重要的. 文档字符串应该提供足够的信息, 当别人编写代码调用该函数时, 他不需要看一行代码, 只要看文档字符串就可以了. 应该给参数单独写文档. 在冒号后跟上解释, 而且应该用统一的悬挂式2或4空格缩进. 文档字符串应该在需要特定类型的地方指定期望的类型.
“Raise:”部分应该列出该函数可能触发的所有异常. 生成器函数的文档字符串应该用”Yields:”而非”Returns:”.

yes
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

类应该在其定义下有一个用于描述该类的文档字符串. 如果你的类有公共属性(Attributes), 那么文档中应该有一个属性(Attributes)段. 并且应该遵守和函数参数相同的格式.

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

块注释和行注释

最需要写注释的是代码中那些技巧性的部分. 如果你在下次代码走查的时候必须解释一下, 那么你应该现在就给它写注释. 对于复杂的操作, 应该在其操作开始前写上若干行注释. 对于不是一目了然的代码, 应在其行尾添加注释.

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

为了提高可读性, 注释应该至少离开代码2个空格.

另一方面, 绝不要描述代码. 假设阅读代码的人比你更懂Python, 他只是不知道你的代码要做什么.

No
# BAD COMMENT: Now go through the b array and make sure whenever i occurs
# the next element is i+1

小提示
如果一个类不继承自其它类, 就显式的从object继承. 嵌套类也一样
Yes
class SampleClass(object):
    pass


class OuterClass(object):

    class InnerClass(object):
        pass


class ChildClass(ParentClass):
    """Explicitly inherits from another class already."""
No

抱歉!评论已关闭.