python学习

Google Python 编程风格规范

2015-07-24  本文已影响1778人  LittleWizard

参考

--Google Python Style Guide

--Google Python 风格指南 - 中文版

分号

行长度

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</code></pre>

括号

缩进

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)</code></pre>

空行

空格

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</code></pre>

注释

函数和方法

<pre><code>如果不是既显然又简短, 任何函数或方法都需要一个文档字符串. 而且, 任何外部可访问的
函数或方法, 不管多短多简单, 都需要文档字符串. 文档字符串应该包含函数做什么, 以及
输入和输出的详细描述. 通常, 不应该描述”怎么做”, 除非是一些复杂的算法. 对于技巧
性的代码, 块注释或者行内注释是最重要的. 文档字符串应该提供足够的信息, 当别人编写
代码调用该函数时, 他不需要看一行代码, 只要看文档字符串就可以了. 应该给参数单独写
文档. 在冒号后跟上解释, 而且应该用统一的悬挂式2 或4空格缩进. 文档字符串应该在需要
特定类型的地方指定期望的类型. “Raise:”部分应该列出该函数可能触发的所有异常. 生
成器函数的文档字符串应该用”Yields:”而非”Returns:”.
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
类(classes)
类应该在其定义下有一个用于描述该类的文档字符串. 如果你的类有公共属性
(Attributes), 那么文档中应该有一个属性(Attributes)段. 并且应该遵守和函数参数相
同的格式.
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."""
块注释和行注释(Block and Inline Comments)
最需要写注释的是代码中那些技巧性的部分. 如果你在下次代码走查的时候必须解释一
下, 那么你应该现在就给它写注释. 对于复杂的操作, 应该在其操作开始前写上若干行
注释. 对于不是一目了然的代码, 应在其行尾添加注释.
# 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, 他只是不知道你的代码要
做什么.

BAD COMMENT: Now go through the b array and make sure whenever i occurs

the next element is i+1</code></pre>

字符串

TODO 注释

TODO(kl@gmail.com): Drop the use of "has_key".

TODO(Zeke) change this to use relations.

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

导入格式

语句

访问控制

命名

<pre><code>module_name, package_name,
ClassName, method_name, ExceptionName, function_name,
GLOBAL_VAR_NAME,
instance_var_name, function_parameter_name, local_var_name.

应该避免的名称

  1. 单字母名称, 除了计数器和迭代器.
  2. 包/模块名中的连字符(-)
  3. 双下划线开头并结尾的名称(Python 保留, 例如init)
    命名约定
  4. 所谓”内部(Internal)”表示仅模块内可用, 或者, 在类内是保护或私有的.
  5. 用单下划线(_)开头表示模块变量或函数是protected 的(使用import * from
    时不会包含).
  6. 用双下划线(__)开头的实例变量或方法表示类内私有.
  7. 将相关的类和顶级函数放在同一个模块里. 不像Java, 没必要限制一个类一
    个模块.
  8. 对类名使用大写字母开头的单词(如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

Main
即使是一个打算被用作脚本的文件, 也应该是可导入的. 并且简单的导入不应该导致这
个脚本的主功能(main functionality)被执行, 这是一种副作用. 主功能应该放在一个
main()函数中.
在Python 中, pychecker, pydoc 以及单元测试要求模块必须是可导入的. 你的代码应该
在执行主程序前总是检查 if name == 'main' , 这样当模块被导入时主程序就不会
被执行.
def main():
...
if name == 'main':
main()
所有的顶级代码在模块导入时都会被执行. 要小心不要去调用函数, 创建对象, 或者执行那
些不应该在使用pychecker 或pydoc 时执行的操作.</code></pre>

上一篇 下一篇

猜你喜欢

热点阅读