一篇 针对Python开发的“最佳实践精选”指南。
感觉合理的话,就遵循PEP 8。
小写,并使用下划线分隔单词(lower_case_with_underscores)
首字母大写(CapWords)
单下划线开头(_single_leading_underscore(self, …))
双下划线开头(__double_leading_underscore(self, …))
字母全部大写,单词间用下划线分隔(ALL_CAPS_WITH_UNDERSCORES)
尽量不要使用只有一个字母的变量名(例如,l,I,O等)。
例外:在很简短的代码块中,如果变量名的意思可以从上下文明显地看出来。
没问题
12 | for e in elements: e.mutate() |
避免冗余描述。
正确的做法
1234 | import audio core = audio.Core()controller = audio.Controller() |
错误的做法
1234 | import audio core = audio.AudioCore()controller = audio.AudioController() |
“反向记法”更好。
正确的做法
123 | elements = ...elements_active = ...elements_defunct = ... |
错误的做法
123 | elements = ...active_elements = ...defunct_elements ... |
避免使用getter和setter方法。
正确的做法
1 | person.age = 42 |
错误的做法
1 | person.set_age(42) |
用4个空格符——永远别用Tab制表符。就说这么多。
引用整个模块,而不是模块中的单个标识符。举个例子,假设一个cantee模块下面,有一个sessions.py文件,
正确的做法
123 | import canteenimport canteen.sessionsfrom canteen import sessions |
错误的做法
12 | from canteen import get_user # Symbol from canteen/__init__.pyfrom canteen.sessions import get_session # Symbol from canteen/sessions.py |
例外:如果第三方代码的文档中明确说明要单个引用。
理由:避免循环引用。看这里。
把代码引用部分放在文件的顶部,按下面的顺序分成三个部分,每个部分之间空一行。
理由:明确显示每个模块的引用来源。
遵循PEP 257提出的文档字符串准则。reStructuredText (reST) 和Sphinx有助于确保文档符合标准。
对于功能明显的函数,撰写一行文档字符串。
1 | \”\”\”返回“foo“的路径名.\”\”\” |
多行文档字符串应包括:
None
“””训练模型,用来对Foo和Bar分类。用法::
1234567891011 | \”\”\”Train a model to classify Foos and Bars. Usage:: >>> import klassify >>> data = [(\”green\”, \”foo\”), (\”orange\”, \”bar\”)] >>> classifier = klassify.train(data) :param train_data: `(color, label)`形式的一个元组列表。:rtype: A :class:`Classifier |
注意
使用主动词(“返回”),而不是描述性的单词(“返回值”)。 在类的文档字符串中为__init__
方法撰写文档。
123456789 | class Person(object): \”\”\”A simple representation of a human being. :param name: A string, the person\’s name. :param age: An int, the person\’s age. \”\”\” def __init__(self, name, age): self.name = name self.age = age |
尽量少用。与其写很多注释,不如提高代码可读性。通常情况下,短小的方法比注释更有效。
错误的做法
123 | # If the sign is a stop signif sign.color == \’red\’ and sign.sides == 8: stop() |
正确的做法
12345 | def is_stop_sign(sign): return sign.color == \’red\’ and sign.sides == 8 if is_stop_sign(sign): stop() |
但是的确要写注释时,请牢记:“遵循斯托克与怀特所写的《英文写作指南》。” —— PEP 8
不要过分在意。80到100个字符都是没问题的。
使用括号延续当前行。
123456 | wiki = ( \”The Colt Python is a .357 Magnum caliber revolver formerly manufactured \” \”by Colt\’s Manufacturing Company of Hartford, Connecticut. It is sometimes \” \’referred to as a \”Combat Magnum\”. It was first introduced in 1955, the \’ \”same year as Smith & Wesson\’s M29 .44 Magnum.\”) |
尽量争取测试全部代码,但也不必执着于覆盖率。
assert False, \"TODO: finish me\"
。123456789 | import unittestimport factories class PersonTest(unittest.TestCase): def |