Google Python Coding Standards Guide

I PythonGao. A Microsoft engineer. Today to share with you Google Python programming specifications. Suitable for beginners to learn.

semicolon

Do not add a semicolon end of the line, do not use semicolons two commands on the same line.

Line length

Each row is not more than 80 characters

exception:

Long import module statement

Notes in the URL

Do not use the backslash connection line.

Python would parentheses, brackets and braces in a row implicit connected, you can use this feature. If necessary, you can add an extra pair of parentheses in the expression periphery

13717038-e1811b72b74cb169.png
image

If the line does not fit in a text string, parentheses may be used to achieve implicit line joining:

13717038-89567801e8039f16.png
image

In the notes, if necessary, the long URL on a single line.

13717038-eaa33d59e24449d9.png
image

Note that the above examples of the elements in the indentation; you can find an explanation in the indented section of this article.

brackets

Ningquewulan parentheses

Unless it is used to achieve line connection, do not use parentheses in return statements or conditional statements. However, the use of brackets on both sides of the tuple is possible

13717038-47731aed4bc5610d.png
image

indentation

With four spaces to indent your code

Never use tab, tab and space do not mix. In the case of line connection elements you should either vertically aligned line feed (see Example section line length), or using a hanging indent 4 spaces (in this case the first row there should be no argument):

13717038-59bcba12bc089d83.png
image

Blank line

Blank blank line between the top two lines between definitions, methods defined

Space between the top two lines of the definition, such as function or class definition between method definitions, class definitions, and the first method, should be a blank line. Function or method in some places if you feel appropriate, on a blank line.

Blank

According to standard specifications for use layout space on both sides of punctuation

Do not have a space in parentheses.

13717038-789572f80ddb2b39.png
image

Do not commas, semicolons, colons spaces in front of, but should be added (except at the end) behind them.

13717038-6717be39117828e7.png
image

Parameter list, before the opening parenthesis index or slices should not spaces.

13717038-9852a7ce3c77d382.png
image

In binary operators on both sides with a space, such as the assignment (=), compare (==, <,>,! =, <>, <=,> =, In, not in, is, is not), boolean (and, or, not). As to how both sides of the arithmetic operators that use spaces, you need a good judge, but be sure to be consistent on both sides.

13717038-21e2483e95bf421a.png
image

When the '=' is used to indicate a keyword default parameters or parameter values, do not use a space on both sides thereof.

13717038-705a7b50a3f0004a.png
image

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

13717038-bd2513ad7a70c89e.png
image

Shebang

大部分.py文件不必以#!作为文件的开始. 根据 PEP-394 , 程序的main文件应该以 #!/usr/bin/python2或者 #!/usr/bin/python3开始.

(译者注: 在计算机科学中, Shebang (也称为Hashbang)是一个由井号和叹号构成的字符串行(#!), 其出现在文本文件的第一行的前两个字符. 在文件中存在Shebang的情况下, 类Unix操作系统的程序载入器会分析Shebang后的内容, 将这些内容作为解释器指令, 并调用该指令, 并将载有Shebang的文件路径作为该解释器的参数. 例如, 以指令#!/bin/sh开头的文件在执行时会实际调用/bin/sh程序.)

先用于帮助内核找到Python解释器, 但是在导入模块时, 将会被忽略. 因此只有被直接执行的文件中才有必要加入

注释

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

文档字符串

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

模块

每个文件应该包含一个许可样板. 根据项目使用的许可(例如, Apache 2.0, BSD, LGPL, GPL), 选择合适的样板.

函数和方法

下文所指的函数,包括函数, 方法, 以及生成器.

一个函数必须要有文档字符串, 除非它满足以下条件:

外部不可见

非常短小

简单明了

文档字符串应该包含函数做什么, 以及输入和输出的详细描述. 通常, 不应该描述”怎么做”, 除非是一些复杂的算法. 文档字符串应该提供足够的信息, 当别人编写代码调用该函数时, 他不需要看一行代码, 只要看文档字符串就可以了. 对于复杂的代码, 在代码旁边加注释会比使用文档字符串更有意义.

关于函数的几个方面应该在特定的小节中进行描述记录, 这几个方面如下文所述. 每节应该以一个标题行开始. 标题行以冒号结尾. 除标题行外, 节的其他内容应被缩进2个空格.

Args:

列出每个参数的名字, 并在名字后使用一个冒号和一个空格, 分隔对该参数的描述.如果描述太长超过了单行80字符,使用2或者4个空格的悬挂缩进(与文件其他部分保持一致). 描述应该包括所需的类型和含义. 如果一个函数接受foo(可变长度参数列表)或者bar (任意关键字参数), 应该详细列出foo和**bar.

Returns: (或者 Yields: 用于生成器)

描述返回值的类型和语义. 如果函数返回None, 这一部分可以省略.

Raises:

列出与接口有关的所有异常.

13717038-301c541a113b91ae.png
image

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

13717038-3630480196c74b96.png
image

块注释和行注释

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

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.

ifi&(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

如果一个类不继承自其它类, 就显式的从object继承. 嵌套类也一样.

13717038-f26cac34dd9588f5.png
image

继承自object是为了使属性(properties)正常工作, 并且这样可以保护你的代码, 使其不受 PEP-3000 的一个特殊的潜在不兼容性影响. 这样做也定义了一些特殊的方法, 这些方法实现了对象的默认语义, 包括new,init,delattr,getattribute,setattr,hash,repr,and__str__.

字符串

即使参数都是字符串, 使用%操作符或者格式化方法格式化字符串. 不过也不能一概而论, 你需要在+和%之间好好判定.

13717038-ad6db6abfac1a990.png
image

避免在循环中用+和+=操作符来累加字符串. 由于字符串是不可变的, 这样做会创建不必要的临时对象, 并且导致二次方而不是线性的运行时间. 作为替代方案, 你可以将每个子串加入列表, 然后在循环结束后用 .join 连接列表. (也可以将每个子串写入一个 cStringIO.StringIO 缓存中.)

13717038-227a3bde6e5e07f4.png
image

在同一个文件中, 保持使用字符串引号的一致性. 使用单引号’或者双引号”之一用以引用字符串, 并在同一文件中沿用. 在字符串内可以使用另外一种引号, 以避免在字符串中使用. GPyLint已经加入了这一检查.

(译者注:GPyLint疑为笔误, 应为PyLint.)

13717038-c6aeb2de2d2813a5.png
image

为多行字符串使用三重双引号”“”而非三重单引号’‘’. 当且仅当项目中使用单引号’来引用字符串时, 才可能会使用三重’‘’为非文档字符串的多行字符串来标识引用. 文档字符串必须使用三重双引号”“”. 不过要注意, 通常用隐式行连接更清晰, 因为多行字符串与程序其他部分的缩进方式不一致.

13717038-c2adcc9c369d7021.png
image

文件和sockets

在文件和sockets结束时, 显式的关闭它.

除文件外, sockets或其他类似文件的对象在没有必要的情况下打开, 会有许多副作用, 例如:

它们可能会消耗有限的系统资源, 如文件描述符. 如果这些资源在使用后没有及时归还系统, 那么用于处理这些对象的代码会将资源消耗殆尽.

持有文件将会阻止对于文件的其他诸如移动、删除之类的操作.

仅仅是从逻辑上关闭文件和sockets, 那么它们仍然可能会被其共享的程序在无意中进行读或者写操作. 只有当它们真正被关闭后, 对于它们尝试进行读或者写操作将会抛出异常, 并使得问题快速显现出来.

而且, 幻想当文件对象析构时, 文件和sockets会自动关闭, 试图将文件对象的生命周期和文件的状态绑定在一起的想法, 都是不现实的. 因为有如下原因:

没有任何方法可以确保运行环境会真正的执行文件的析构. 不同的Python实现采用不同的内存管理技术, 比如延时垃圾处理机制. 延时垃圾处理机制可能会导致对象生命周期被任意无限制的延长.

对于文件意外的引用,会导致对于文件的持有时间超出预期(比如对于异常的跟踪, 包含有全局变量等).

推荐使用 “with”语句 以管理文件:

13717038-96c431fb456ecf31.png
image

对于不支持使用”with”语句的类似文件的对象,使用 contextlib.closing():

13717038-1e53c7f2f4b68be6.png
image

Legacy AppEngine 中Python 2.5的代码如使用”with”语句, 需要添加 “from future import with_statement”.

TODO注释

为临时代码使用TODO注释, 它是一种短期解决方案. 不算完美, 但够好了.

TODO注释应该在所有开头处包含”TODO”字符串, 紧跟着是用括号括起来的你的名字, email地址或其它标识符. 然后是一个可选的冒号. 接着必须有一行注释, 解释要做什么. 主要目的是为了有一个统一的TODO格式, 这样添加注释的人就可以搜索到(并可以按需提供更多细节). 写了TODO注释并不保证写的人会亲自解决问题. 当你写了一个TODO, 请注上你的名字.

13717038-48f12e6e6c4e5ad3.png
image

如果你的TODO是”将来做某事”的形式, 那么请确保你包含了一个指定的日期(“2009年11月解决”)或者一个特定的事件(“等到所有的客户都可以处理XML请求就移除这些代码”).

导入格式

每个导入应该独占一行

13717038-f7512654a21be0aa.png
image

导入总应该放在文件顶部, 位于模块注释和文档字符串之后, 模块全局变量和常量之前. 导入应该按照从最通用到最不通用的顺序分组:

标准库导入

第三方库导入

应用程序指定导入

每种分组中, 应该根据每个模块的完整包路径按字典序排序, 忽略大小写.

13717038-0083f32503fc8d6a.png
image

语句

通常每个语句应该独占一行

不过, 如果测试结果与测试语句在一行放得下, 你也可以将它们放在同一行. 如果是if语句, 只有在没有else时才能这样做. 特别地, 绝不要对try/except这样做, 因为try和except不能放在同一行.

13717038-7920e5ad36a205f7.png
image

访问控制

在Python中, 对于琐碎又不太重要的访问函数, 你应该直接使用公有变量来取代它们, 这样可以避免额外的函数调用开销. 当添加更多功能时, 你可以用属性(property)来保持语法的一致性.

(译者注: 重视封装的面向对象程序员看到这个可能会很反感, 因为他们一直被教育: 所有成员变量都必须是私有的! 其实, 那真的是有点麻烦啊. 试着去接受Pythonic哲学吧)

另一方面, 如果访问更复杂, 或者变量的访问开销很显著, 那么你应该使用像get_foo()和set_foo()这样的函数调用. 如果之前的代码行为允许通过属性(property)访问 , 那么就不要将新的访问函数与属性绑定. 这样, 任何试图通过老方法访问变量的代码就没法运行, 使用者也就会意识到复杂性发生了变化.

命名

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的(使用from module import *时不会包含).

用双下划线(__)开头的实例变量或方法表示类内私有.

The related classes and top-level functions in the same module. Unlike Java, a class is not necessary to limit a module.

The use of class names begin with a capital letter word (such as CapWords, namely Pascal style), but the module name should be in lower case underlined the way (such as lower_with_under.py). Although there are many existing modules such use similar CapWords.py named, but now is not encouraged, because if it happens module name and the name of the same class, which will be annoying.

Father Guido Python's recommended practices

13717038-5ee0c9fa7d68b750.png
image

Main

Even a script file is used as intended, it should also be available for import. Import and should not lead to a simple main function of the script (main functionality) is executed, which is a side effect. Main function should be placed in a main () function.

In Python, pydoc test requirements and a unit module must be imported. The code you should always check if__name __ == 'before executing the main program main ', so that when the main program will not be executed when the module is introduced.

13717038-09a9a4a39b1152aa.png
image

All top-level code will be executed when the module is imported. Be careful not to call the function that creates an object, or perform those operations should not be performed when using pydoc.

The above is recommended that you google the Python coding standards.

Reproduced in: https: //www.jianshu.com/p/d52bb4585abe

Guess you like

Origin blog.csdn.net/weixin_33777877/article/details/91310330