🚀 原文地址:https://zh-google-styleguide.readthedocs.io/en/latest/google-python-styleguide/python_style_rules/
1. 分号
2. 行长度
每行不超过 80 个字符,但是下面这些情况除外:
- 长的导入模块语句
- 注释里的 URL,路径以及其他的一些长标记
- 不便于换行,不包含空格的模块级字符串常量,比如 url 或者路径
- Pylint 禁用注释(例如:
# pylint: disable=invalid-name)
除非是在 with 语句需要三个以上的上下文管理器的情况下,否则不要使用反斜杠连接行。
Python会将圆括号、中括号和花括号中的行隐式的连接起来 , 你可以利用这个特点。如果需要,你可以在表达式外围增加一对额外的圆括号。
foo_bar(self, width, height, color='black', design=None, x='foo',emphasis=None, highlight=0)if (width == 0 and height == 0 andcolor == 'red' and emphasis == 'strong'):
如果一个文本字符串在一行放不下,可以使用圆括号来实现隐式行连接:
x = ('This will build a very long long ''long long long long long long string')
在注释中,如果必要,将长的URL放在一行上。
# See details at# http://www.example.com/us/developer/documentation/api/content/v2.0/csv_file_name_extension_full_specification.html
# See details at# http://www.example.com/us/developer/documentation/api/content/\# v2.0/csv_file_name_extension_full_specification.html
当 with 表达式需要使用三个及其以上的上下文管理器时,可以使用反斜杠换行。若只需要两个,请使用嵌套的with:
with very_long_first_expression_function() as spam, \very_long_second_expression_function() as beans, \third_thing() as eggs:place_order(eggs, beans, spam, beans)
with VeryLongFirstExpressionFunction() as spam, \VeryLongSecondExpressionFunction() as beans:PlaceOrder(eggs, beans, spam, beans)
with very_long_first_expression_function() as spam:with very_long_second_expression_function() as beans:place_order(beans, spam)
注意上面例子中的元素缩进,你可以在本文的缩进部分找到解释。
另外在其他所有情况下,若一行超过 80 个字符,但 yapf 却无法将该行字数降至 80 个字符以下时,则允许该行超过80个字符长度。
3. 括号
宁缺毋滥的使用括号,除非是用于实现行连接,否则不要在返回语句或条件语句中使用括号。不过在元组两边使用括号是可以的。
if foo:bar()while x:x = bar()if x and y:bar()if not x:bar()# For a 1 item tuple the ()s are more visually obvious than the comma.onesie = (foo,)return fooreturn spam, beansreturn (spam, beans)for (x, y) in dict.items(): ...
if (x):bar()if not(x):bar()return (foo)
4. 缩进
用 4 个空格来缩进代码,绝对不要用 tab,也不要 tab 和空格混用。对于行连接的情况,你应该要么垂直对齐换行的元素(见 行长度部分的示例),或者使用 4 空格的悬挂式缩进(这时第一行不应该有参数):
# Aligned with opening delimiterfoo = long_function_name(var_one, var_two,var_three, var_four)# Aligned with opening delimiter in a dictionaryfoo = {long_dictionary_key: value1 +value2,...}# 4-space hanging indent; nothing on first linefoo = long_function_name(var_one, var_two, var_three,var_four)# 4-space hanging indent in a dictionaryfoo = {long_dictionary_key:long_dictionary_value,...}
# Stuff on first line forbiddenfoo = long_function_name(var_one, var_two,var_three, var_four)# 2-space hanging indent forbiddenfoo = long_function_name(var_one, var_two, var_three,var_four)# No hanging indent in a dictionaryfoo = {long_dictionary_key:long_dictionary_value,...}
5. 序列元素尾部逗号
仅当 ]、)、} 和末位元素不在同一行时,推荐使用序列元素尾部逗号。当末位元素尾部有逗号时,元素后的逗号可以指示 YAPF 将序列格式化为每行一项。
golomb3 = [0, 1, 3]golomb4 = [0,1,4,6,]
golomb4 = [0,1,4,6]
6. 空行
顶级定义之间空两行,方法定义之间空一行。
顶级定义之间空两行,比如函数或者类定义。方法定义,类定义与第一个方法之间,都应该空一行。函数或方法中,某些地方要是你觉得合适,就空一行。
7. 空格
按照标准的排版规范来使用标点两边的空格,括号内不要有空格:
spam(ham[1], {eggs: 2}, [])
spam( ham[ 1 ], { eggs: 2 }, [ ] )
不要在逗号、分号、冒号前面加空格,但应该在它们后面加(除了在行尾)。
if x == 4:print(x, y)x, y = y, x
if x == 4 :print(x , y)x , y = y , x
参数列表、索引或切片的左括号前不应加空格:
spam(1)dict['key'] = list[index]
spam (1)dict ['key'] = list [index]
在二元操作符两边都加上一个空格,比如赋值(=)、比较(==、<、>、!=、<>、<=、>=、in、not in、is、is not)、布尔(and、or、not)。至于算术操作符两边的空格该如何使用,需要你自己好好判断。不过两侧务必要保持一致:
x == 1
x<1
当 = 用于指示关键字参数或默认参数值时,不要在其两侧使用空格。但若存在类型注释的时候,需要在 = 周围使用空格。
def complex(real, imag=0.0): return magic(r=real, i=imag)def complex(real, imag: float = 0.0): return Magic(r=real, i=imag)
def complex(real, imag = 0.0): return magic(r = real, i = imag)def complex(real, imag: float=0.0): return Magic(r = real, i = imag)
不要用空格来垂直对齐多行间的标记,因为这会成为维护的负担(适用于:、#、=等):
foo = 1000 # commentlong_name = 2 # comment that should not be aligneddictionary = {"foo": 1,"long_name": 2,}
foo = 1000 # commentlong_name = 2 # comment that should not be aligneddictionary = {"foo" : 1,"long_name": 2,}
8. Shebang
大部分.py 文件不必以#!作为文件的开始,根据 PEP-394,程序的 main 文件应该以 #!/usr/bin/python2 或者 #!/usr/bin/python3 开始。
:::warning
💡Tips
——————————————
在计算机科学中,Shebang (也称为Hashbang) 是一个由井号和叹号构成的字符串行(#!),其出现在文本文件的第一行的前两个字符。在文件中存在 Shebang 的情况下,类 Unix 操作系统的程序载入器会分析 Shebang 后的内容,将这些内容作为解释器指令,并调用该指令,并将载有 Shebang 的文件路径作为该解释器的参数。例如,以指令#!/bin/sh开头的文件在执行时会实际调用/bin/sh程序
:::
#! 先用于帮助内核找到 Python 解释器,但是在导入模块时,将会被忽略。因此只有被直接执行的文件中才有必要加入 #!
9. 注释
9.1 文档字符串
Python 有一种独一无二的的注释方式:使用文档字符串。文档字符串是包、模块、类或函数里的第一个语句。这些字符串可以通过对象的 __doc__ 成员被自动提取,并且被 pydoc 所用。 (你可以在你的模块上运行 pydoc 试一把,看看它长什么样)。我们对文档字符串的惯例是使用三重双引号"""( PEP-257 )。一个文档字符串应该这样组织:首先是一行以句号、问号或惊叹号结尾的概述(或者该文档字符串单纯只有一行)。接着是一个空行,接着是文档字符串剩下的部分,它应该与文档字符串的第一行的第一个引号对齐。下面有更多文档字符串的格式化规范。
9.2 模块
每个文件应该包含一个许可样板,根据项目使用的许可(例如 Apache 2.0、BSD、LGPL、GPL),选择合适的样板。其开头应是对模块内容和用法的描述:
"""A one line summary of the module or program, terminated by a period.Leave one blank line. The rest of this docstring should contain anoverall description of the module or program. Optionally, it may alsocontain a brief description of exported classes and functions and/or usageexamples.Typical usage example:foo = ClassFoo()bar = foo.FunctionBar()"""
9.3 函数和方法
下文所指的函数,包括函数, 方法, 以及生成器,一个函数必须要有文档字符串, 除非它满足以下条件:
- 外部不可见
- 非常短小
- 简单明了
文档字符串应该包含函数做什么,以及输入和输出的详细描述。通常,不应该描述”怎么做”,除非是一些复杂的算法。文档字符串应该提供足够的信息,当别人编写代码调用该函数时,他不需要看一行代码,只要看文档字符串就可以了。对于复杂的代码,在代码旁边加注释会比使用文档字符串更有意义。覆盖基类的子类方法应有一个类似 See base class 的简单注释来指引读者到基类方法的文档注释。若重载的子类方法和基类方法有很大不同,那么注释中应该指明这些信息。
关于函数的几个方面应该在特定的小节中进行描述记录, 这几个方面如下文所述。每节应该以一个标题行开始、标题行以冒号结尾,除标题行外、节的其他内容应被缩进 2 个空格。
Args:列出每个参数的名字,并在名字后使用一个冒号和一个空格,分隔对该参数的描述.如果描述太长超过了单行 80 字符,使用 2 或者 4 个空格的悬挂缩进(与文件其他部分保持一致)。描述应该包括所需的类型和含义。如果一个函数接受*foo(可变长度参数列表)或者**bar(任意关键字参数), 应该详细列出*foo和**bar。Returns(或者Yields用于生成器):描述返回值的类型和语义,如果函数返回None,这一部分可以省略。Raises:列出与接口有关的所有异常.
def fetch_smalltable_rows(table_handle: smalltable.Table,keys: Sequence[Union[bytes, str]],require_all_keys: bool = False,) -> Mapping[bytes, Tuple[str]]:"""Fetches rows from a Smalltable.Retrieves rows pertaining to the given keys from the Table instancerepresented by table_handle. String keys will be UTF-8 encoded.Args:table_handle: An open smalltable.Table instance.keys: A sequence of strings representing the key of each tablerow to fetch. String keys will be UTF-8 encoded.require_all_keys: Optional; If require_all_keys is True onlyrows with values set for all keys will be returned.Returns:A dict mapping keys to the corresponding table row datafetched. Each row is represented as a tuple of strings. Forexample:{b'Serak': ('Rigel VII', 'Preparer'),b'Zim': ('Irk', 'Invader'),b'Lrrr': ('Omicron Persei 8', 'Emperor')}Returned keys are always bytes. If a key from the keys argument ismissing from the dictionary, then that row was not found in thetable (and require_all_keys must have been False).Raises:IOError: An error occurred accessing the smalltable."""
def fetch_smalltable_rows(table_handle: smalltable.Table,keys: Sequence[Union[bytes, str]],require_all_keys: bool = False,) -> Mapping[bytes, Tuple[str]]:"""Fetches rows from a Smalltable.Retrieves rows pertaining to the given keys from the Table instancerepresented by table_handle. String keys will be UTF-8 encoded.Args:table_handle:An open smalltable.Table instance.keys:A sequence of strings representing the key of each table row tofetch. String keys will be UTF-8 encoded.require_all_keys:Optional; If require_all_keys is True only rows with values setfor all keys will be returned.Returns:A dict mapping keys to the corresponding table row datafetched. Each row is represented as a tuple of strings. Forexample:{b'Serak': ('Rigel VII', 'Preparer'),b'Zim': ('Irk', 'Invader'),b'Lrrr': ('Omicron Persei 8', 'Emperor')}Returned keys are always bytes. If a key from the keys argument ismissing from the dictionary, then that row was not found in thetable (and require_all_keys must have been False).Raises:IOError: An error occurred accessing the smalltable."""
9.4 块注释和行注释
最需要写注释的是代码中那些技巧性的部分,如果你在下次代码审查的时候必须解释一下,那么你应该现在就给它写注释。对于复杂的操作,应该在其操作开始前写上若干行注释。对于不是一目了然的代码,应在其行尾添加注释。
# 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 if i is 0 or a power of 2.
为了提高可读性,注释应该至少离开代码 2 个空格。另一方面,绝不要描述代码。假设阅读代码的人比你更懂 Python,他只是不知道你的代码要做什么。
# BAD COMMENT: Now go through the b array and make sure whenever i occurs# the next element is i+1
10. 标点符号、拼写和语法
注意标点符号、拼写和语法,注释应有适当的大写和标点,句子应该尽量完整。对于诸如在行尾上的较短注释,可以不那么正式,但是也应该尽量保持风格一致。
11. 类
如果一个类不继承自其它类,就显式的从 object 继承。嵌套类也一样(除非是为了和 Python2 兼容)。
class SampleClass(object):...class OuterClass(object):class InnerClass(object):...class ChildClass(ParentClass):"""Explicitly inherits from another class already."""...
class SampleClass:...class OuterClass:class InnerClass:...
继承自 object 是为了使属性(properties)正常工作,并且这样可以保护你的代码,使其不受 PEP-3000 的一个特殊的潜在不兼容性影响。这样做也定义了一些特殊的方法,这些方法实现了对象的默认语义,包括 __new__、__init__、__delattr__、__getattribute__、__setattr__、__hash__、__repr__ 以及 __str__。
12. 字符串
即使参数都是字符串,使用%操作符或者格式化方法格式化字符串。不过也不能一概而论,你需要在+和%之间好好判定。
x = a + bx = '%s, %s!' % (imperative, expletive)x = '{}, {}!'.format(imperative, expletive)x = 'name: %s; score: %d' % (name, n)x = 'name: {}; score: {}'.format(name, n)
x = '%s%s' % (a, b) # use + in this casex = '{}{}'.format(a, b) # use + in this casex = imperative + ', ' + expletive + '!'x = 'name: ' + name + '; score: ' + str(n)
避免在循环中用+和+=操作符来累加字符串。由于字符串是不可变的,这样做会创建不必要的临时对象,并且导致二次方而不是线性的运行时间。作为替代方案,你可以将每个子串加入列表,然后在循环结束后用 .join 连接列表。(也可以将每个子串写入一个 cStringIO.StringIO 缓存中)
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)
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>'
在同一个文件中,保持使用字符串引号的一致性。使用单引号’或者双引号”之一用以引用字符串,并在同一文件中沿用。在字符串内可以使用另外一种引号,以避免在字符串中使用。
Python('Why are you hiding your eyes?')Gollum("I'm scared of lint errors.")Narrator('"Good!" thought a happy Python reviewer.')
Python("Why are you hiding your eyes?")Gollum('The lint. It burns. It burns us.')Gollum("Always the great lint. Watching. Watching.")
为多行字符串使用三重双引号"""而非三重单引号'''。当且仅当项目中使用单引号'来引用字符串时,才可能会使用三重'''为非文档字符串的多行字符串来标识引用。文档字符串必须使用三重双引号"""。多行字符串不应随着代码其他部分缩进的调整而发生位置移动。如果需要避免在字符串中嵌入额外的空间,可以使用串联的单行字符串或者使用 textwrap.dedent() 来删除每行多余的空间。
long_string = """This is fine if your use case can acceptextraneous leading spaces."""long_string = ("And this is fine if you cannot accept\n" +"extraneous leading spaces.")import textwraplong_string = textwrap.dedent("""\This is also fine, because textwrap.dedent()will collapse common leading spaces in each line.""")
long_string = ("And this too is fine if you cannot accept\n""extraneous leading spaces.")
13. 文件和sockets
在文件和sockets结束时,显式的关闭它。除文件外,sockets或其他类似文件的对象在没有必要的情况下打开,会有许多副作用,例如:
- 它们可能会消耗有限的系统资源,如文件描述符。如果这些资源在使用后没有及时归还系统,那么用于处理这些对象的代码会将资源消耗殆尽。
- 持有文件将会阻止对于文件的其他诸如移动、删除之类的操作。
- 仅仅是从逻辑上关闭文件和sockets,那么它们仍然可能会被其共享的程序在无意中进行读或者写操作。只有当它们真正被关闭后,对于它们尝试进行读或者写操作将会抛出异常,并使得问题快速显现出来。
而且,幻想当文件对象析构时,文件和sockets会自动关闭,试图将文件对象的生命周期和文件的状态绑定在一起的想法,都是不现实的。因为有如下原因:
- 没有任何方法可以确保运行环境会真正的执行文件的析构。不同的 Python 实现采用不同的内存管理技术,比如延时垃圾处理机制,延时垃圾处理机制可能会导致对象生命周期被任意无限制的延长。
对于文件意外的引用,会导致对于文件的持有时间超出预期(比如对于异常的跟踪, 包含有全局变量等).
