Python 风格规范html
main 分号 行长度 括号 缩进 空行 空格 Shebang
python
Tipapi
即便是一个打算被用做脚本的文件, 也应该是可导入的. 而且简单的导入不该该致使这个脚本的主功能(main functionality)被执行, 这是一种反作用. 主功能应该放在一个main()函数中.缓存
在Python中, pydoc以及单元测试要求模块必须是可导入的. 你的代码应该在执行主程序前老是检查if __name__ == '__main__'
, 这样当模块被导入时主程序就不会被执行.app
def main(): ... if __name__ == '__main__': main()
全部的顶级代码在模块导入时都会被执行. 要当心不要去调用函数, 建立对象, 或者执行那些不该该在使用pydoc时执行的操做.socket
Tip函数
不要在行尾加分号, 也不要用分号将两条命令放在同一行.单元测试
Tip
每行不超过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'):
若是一个文本字符串在一行放不下, 可使用圆括号来实现隐式行链接:
x = ('This will build a very long long ' 'long long long long long long string')
在注释中,若是必要,将长的URL放在一行上。
Yes: # See details at # http://www.example.com/us/developer/documentation/api/content/v2.0/csv_file_name_extension_full_specification.html
No: # See details at # http://www.example.com/us/developer/documentation/api/content/\ # v2.0/csv_file_name_extension_full_specification.html
注意上面例子中的元素缩进; 你能够在本文的 缩进 部分找到解释.
Tip
宁缺毋滥的使用括号
除非是用于实现行链接, 不然不要在返回语句或条件语句中使用括号. 不过在元组两边使用括号是能够的.
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)
Tip
用4个空格来缩进代码
绝对不要用tab, 也不要tab和空格混用. 对于行链接的状况, 你应该要么垂直对齐换行的元素(见 行长度 部分的示例), 或者使用4空格的悬挂式缩进(这时第一行不该该有参数):
Yes: # Aligned with opening delimiter foo = long_function_name(var_one, var_two, var_three, var_four) # Aligned with opening delimiter in a dictionary foo = { long_dictionary_key: value1 + value2, ... } # 4-space hanging indent; nothing on first line foo = long_function_name( var_one, var_two, var_three, var_four) # 4-space hanging indent in a dictionary foo = { long_dictionary_key: long_dictionary_value, ... }
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) # No hanging indent in a dictionary foo = { long_dictionary_key: long_dictionary_value, ... }
Tip
顶级定义之间空两行, 方法定义之间空一行
顶级定义之间空两行, 好比函数或者类定义. 方法定义, 类定义与第一个方法之间, 都应该空一行. 函数或方法中, 某些地方要是你以为合适, 就空一行.
Tip
按照标准的排版规范来使用标点两边的空格
括号内不要有空格.
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, }
Tip
大部分.py文件没必要以#!做为文件的开始. 根据 PEP-394 , 程序的main文件应该以 #!/usr/bin/python2或者 #!/usr/bin/python3开始.
(译者注: 在计算机科学中, Shebang (也称为Hashbang)是一个由井号和叹号构成的字符串行(#!), 其出如今文本文件的第一行的前两个字符. 在文件中存在Shebang的状况下, 类Unix操做系统的程序载入器会分析Shebang后的内容, 将这些内容做为解释器指令, 并调用该指令, 并将载有Shebang的文件路径做为该解释器的参数. 例如, 以指令#!/bin/sh开头的文件在执行时会实际调用/bin/sh程序.)
#!先用于帮助内核找到Python解释器, 可是在导入模块时, 将会被忽略. 所以只有被直接执行的文件中才有必要加入#!.
Tip
若是一个类不继承自其它类, 就显式的从object继承. 嵌套类也同样.
Yes: class SampleClass(object): pass class OuterClass(object): class InnerClass(object): pass class ChildClass(ParentClass): """Explicitly inherits from another class already."""
No: class SampleClass: pass class OuterClass: class InnerClass: pass
继承自 object
是为了使属性(properties)正常工做, 而且这样能够保护你的代码, 使其不受Python 3000的一个特殊的潜在不兼容性影响. 这样作也定义了一些特殊的方法, 这些方法实现了对象的默认语义, 包括__new__, __init__, __delattr__, __getattribute__, __setattr__, __hash__, __repr__, and __str__
.
Tip
即便参数都是字符串, 使用%操做符或者格式化方法格式化字符串. 不过也不能一律而论, 你须要在+和%之间好好断定.
Yes: x = a + b x = '%s, %s!' % (imperative, expletive) x = '{}, {}!'.format(imperative, expletive) x = 'name: %s; score: %d' % (name, n) x = 'name: {}; score: {}'.format(name, n)
No: x = '%s%s' % (a, b) # use + in this case x = '{}{}'.format(a, b) # use + in this case x = imperative + ', ' + expletive + '!' x = 'name: ' + name + '; score: ' + str(n)
避免在循环中用+和+=操做符来累加字符串. 因为字符串是不可变的, 这样作会建立没必要要的临时对象, 而且致使二次方而不是线性的运行时间. 做为替代方案, 你能够将每一个子串加入列表, 而后在循环结束后用 .join
链接列表. (也能够将每一个子串写入一个 cStringIO.StringIO
缓存中.)
Yes: items = ['<table>'] for last_name, first_name in employee_list: items.append('<tr><td>%s, %s</td></tr>' % (last_name, first_name)) items.append('</table>') employee_table = ''.join(items)
No: employee_table = '<table>' for last_name, first_name in employee_list: employee_table += '<tr><td>%s, %s</td></tr>' % (last_name, first_name) employee_table += '</table>'
在同一个文件中, 保持使用字符串引号的一致性. 使用单引号’或者双引号”之一用以引用字符串, 并在同一文件中沿用. 在字符串内可使用另一种引号, 以免在字符串中使用. GPyLint已经加入了这一检查.
(译者注:GPyLint疑为笔误, 应为PyLint.)
Yes: Python('Why are you hiding your eyes?') Gollum("I'm scared of lint errors.") Narrator('"Good!" thought a happy Python reviewer.')
No: Python("Why are you hiding your eyes?") Gollum('The lint. It burns. It burns us.') Gollum("Always the great lint. Watching. Watching.")
为多行字符串使用三重双引号”“”而非三重单引号’‘’. 当且仅当项目中使用单引号’来引用字符串时, 才可能会使用三重’‘’为非文档字符串的多行字符串来标识引用. 文档字符串必须使用三重双引号”“”. 不过要注意, 一般用隐式行链接更清晰, 由于多行字符串与程序其余部分的缩进方式不一致.
Yes: print ("This is much nicer.\n" "Do it this way.\n")
No: print """This is pretty ugly. Don't do this. """
Tip
在文件和sockets结束时, 显式的关闭它.
除文件外, sockets或其余相似文件的对象在没有必要的状况下打开, 会有许多反作用, 例如:
并且, 幻想当文件对象析构时, 文件和sockets会自动关闭, 试图将文件对象的生命周期和文件的状态绑定在一块儿的想法, 都是不现实的. 由于有以下缘由:
推荐使用 “with”语句 以管理文件:
with open("hello.txt") as hello_file: for line in hello_file: print line
对于不支持使用”with”语句的相似文件的对象,使用 contextlib.closing():
import contextlib with contextlib.closing(urllib.urlopen("http://www.python.org/")) as front_page: for line in front_page: print line
Legacy AppEngine 中Python 2.5的代码如使用”with”语句, 须要添加 “from __future__ import with_statement”.
Tip
为临时代码使用TODO注释, 它是一种短时间解决方案. 不算完美, 但够好了.
TODO注释应该在全部开头处包含”TODO”字符串, 紧跟着是用括号括起来的你的名字, email地址或其它标识符. 而后是一个可选的冒号. 接着必须有一行注释, 解释要作什么. 主要目的是为了有一个统一的TODO格式, 这样添加注释的人就能够搜索到(并能够按需提供更多细节). 写了TODO注释并不保证写的人会亲自解决问题. 当你写了一个TODO, 请注上你的名字.
# TODO(kl@gmail.com): Use a "*" here for string repetition.
# TODO(Zeke) Change this to use relations.
若是你的TODO是”未来作某事”的形式, 那么请确保你包含了一个指定的日期(“2009年11月解决”)或者一个特定的事件(“等到全部的客户均可以处理XML请求就移除这些代码”).
Tip
每一个导入应该独占一行
Yes: import os import sys
No: import os, sys
导入总应该放在文件顶部, 位于模块注释和文档字符串以后, 模块全局变量和常量以前. 导入应该按照从最通用到最不通用的顺序分组:
每种分组中, 应该根据每一个模块的完整包路径按字典序排序, 忽略大小写.
import foo from foo import bar from foo.bar import baz from foo.bar import Quux from Foob import ar
Tip
一般每一个语句应该独占一行
不过, 若是测试结果与测试语句在一行放得下, 你也能够将它们放在同一行. 若是是if语句, 只有在没有else时才能这样作. 特别地, 毫不要对 try/except
这样作, 由于try和except不能放在同一行.
Yes: if foo: bar(foo)
No: if foo: bar(foo) else: baz(foo) try: bar(foo) except ValueError: baz(foo) try: bar(foo) except ValueError: baz(foo)
Tip
在Python中, 对于琐碎又不过重要的访问函数, 你应该直接使用公有变量来取代它们, 这样能够避免额外的函数调用开销. 当添加更多功能时, 你能够用属性(property)来保持语法的一致性.
(译者注: 重视封装的面向对象程序员看到这个可能会很反感, 由于他们一直被教育: 全部成员变量都必须是私有的! 其实, 那真的是有点麻烦啊. 试着去接受Pythonic哲学吧)
另外一方面, 若是访问更复杂, 或者变量的访问开销很显著, 那么你应该使用像 get_foo()
和 set_foo()
这样的函数调用. 若是以前的代码行为容许经过属性(property)访问 , 那么就不要将新的访问函数与属性绑定. 这样, 任何试图经过老方法访问变量的代码就无法运行, 使用者也就会意识到复杂性发生了变化.
Tip
module_name, package_name, ClassName, method_name, ExceptionName, function_name, GLOBAL_VAR_NAME, instance_var_name, function_parameter_name, local_var_name.
应该避免的名称
- 单字符名称, 除了计数器和迭代器.
- 包/模块名中的连字符(-)
- 双下划线开头并结尾的名称(Python保留, 例如__init__)
命名约定
- 所谓”内部(Internal)”表示仅模块内可用, 或者, 在类内是保护或私有的.
- 用单下划线(_)开头表示模块变量或函数是protected的(使用import * from时不会包含).
- 用双下划线(__)开头的实例变量或方法表示类内私有.
- 将相关的类和顶级函数放在同一个模块里. 不像Java, 不必限制一个类一个模块.
- 对类名使用大写字母开头的单词(如CapWords, 即Pascal风格), 可是模块名应该用小写加下划线的方式(如lower_with_under.py). 尽管已经有不少现存的模块使用相似于CapWords.py这样的命名, 但如今已经不鼓励这样作, 由于若是模块名碰巧和类名一致, 这会让人困扰.
Python之父Guido推荐的规范
Type | Public | Internal |
---|---|---|
Modules | lower_with_under | _lower_with_under |
Packages | lower_with_under | |
Classes | CapWords | _CapWords |
Exceptions | CapWords | |
Functions | lower_with_under() | _lower_with_under() |
Global/Class Constants | CAPS_WITH_UNDER | _CAPS_WITH_UNDER |
Global/Class Variables | lower_with_under | _lower_with_under |
Instance Variables | lower_with_under | _lower_with_under (protected) or __lower_with_under (private) |
Method Names | lower_with_under() | _lower_with_under() (protected) or __lower_with_under() (private) |
Function/Method Parameters | lower_with_under | |
Local Variables | lower_with_under |
注释
Tip
确保对模块, 函数, 方法和行内注释使用正确的风格
文档字符串
模块
函数和方法
类
块注释和行注释