Python Style Guide
Python Language Rules
Run
pylintover your code run from terminalpylint xxxx.pysome warnings might be inappropriate - need to supressdict = 'something awful' # Bad Idea... pylint: disable=redefined-builtinUse
importfor packages and modules only- Use
import xfor importing packages and modules. - Use
from x import ywhere x is the package prefix and y is the module name with no prefix. - Use
from x import y as zif two modules named y are to be imported or if y is an inconveniently long name.
Do not use relative names in imports. Even if the module is in the same package, use the full package name. This helps prevent unintentionally importing a package twice.
- Use
- Import each module using the full pathname location of the module.
# Reference in code with complete name.
import sound.effects.echo
# Reference in code with just module name (preferred).
from sound.effects import echo
- Exceptions are allowed but must be used carefully.
Exceptions must follow certain conditions:
- Raise exceptions like this:
raise MyException('Error message')orraise MyException. Do not use the two-argument form (raise MyException, 'Error message') or deprecated string-based exceptions (raise 'Error message'). - Modules or packages should define their own domain-specific base exception class, which should inherit from the built-in Exception class.
- Never use catch-all
except: statements, or catchExceptionorStandardError, - Minimize the amount of code in a
try/exceptblock.
- Raise exceptions like this:
- Avoid global variables.
- Nested/local/inner classes and functions are fine.
- List Comprehensions - Okay to use for simple cases.
NOT FINISHED
Python Style Rules
- 不用分毫
;, 不要用分号将两条语句连在一行 - 每行最长80个字符,
例外
import语句本身很长- 注释中有很长的URL 不要用反斜杠,在括号、方括号、大括号内换行,可以额外增加括号将语句包在内部
- 尽量少用括号
不要用在在
return和ifstatement后面(除非是为了连接不同行) - 用4个空格来缩进,不用Tab,不要空格和Tab混用 In cases of implied line continuation, you should align wrapped elements either vertically, as per the examples in the line length section; or using a hanging indent of 4 spaces, in which case there should be no argument on the first line.
- 空白行 Two blank lines between top-level definitions, be they function or class definitions. One blank line between method definitions and between the class line and the first method. Use single blank lines as you judge appropriate within functions or methods.
- 空格
- 括号、中括号和大括号内不留空格
- 逗号、分号和冒号之前不留空格,后面要留空格(除非符号在句末)
- No whitespace before the open paren/bracket that starts an argument list, indexing or slicing.
- Surround binary operators with a single space on either side for assignment (=), comparisons (==, <, >, !=, <>, <=, >=, in, not in, is, is not), and Booleans (and, or, not). Use your better judgment for the insertion of spaces around arithmetic operators but always be consistent about whitespace on either side of a binary operator.
- Don't use spaces around the '=' sign when used to indicate a keyword argument or a default parameter value.
- Don't use spaces to vertically align tokens on consecutive lines, since it becomes a maintenance burden (applies to :, #, =, etc.)
- 注释
- Doc Strings
- moduls - Choose the appropriate boilerplate for the license used by the project (for example, Apache 2.0, BSD, LGPL, GPL)
- functions and methods 必须要有docstrings, 除非是及其简单的或者外界无法见到的。需要包含以下部分: Args, Returns, Raises
- Classes, 需要包含解释和Attributes说明
- Block and inline comments
- Doc Strings
- 类
If a class inherits from no other base classes, explicitly inherit from
object. This also applies to nested classes. - 字符串
- 使用
format方法或者%操作符来设置字符串格式;明智判断何时该用+连接符还是用%orformat - 在loop中不要使用
+或者+=来连接字符串。将需要连接的用list存储并在loop结束后使用.join()。原因在于:strings是immutable,会导致产生不必要的临时objects导致quadratic rather than linear running time. - 对单引号或双引号但使用要一致
- 长字符串使用
"""而不是''';docstrings仅能使用""";另外注意如果可以利用括号将长字符串分行写;引号内的多好字符串会打乱代码缩紧的模式。
- 使用
- 使用完文档或sockets之后要关闭 尽量使用
with语句 - TODO Comments
# TODO([email protected] Fix by Date / Remove after XXX): explanation - imports 用不同行导入不同模块;代码最开始部分; 按照这样的顺序:standard library imports, 3rd party imports, application-specific imports
- 语句
一般情况下每行一个语句;如果是简单的
if语句可以放在一行 - Access Control(TBA)
命名
module_name, package_name, ClassName, method_name, ExceptionName, function_name, GLOBAL_CONSTANT_NAME, global_var_name, instance_var_name, function_parameter_name, local_var_name不要这样命名
- single character names except for counters or iterators
- dashes (-) in any package/module name
__double_leading_and_trailing_underscore__names (reserved by Python)
命名规范 Guidelines derived from Guido's Recommendations
| Type | Public | Internal |
|---|---|---|
| Packages | lower_with_under | |
| Modules | lower_with_under | _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语句importable
def main():
...
if __name__ == '__main__':
main()
Change logs
2017.02.24 Initial Draft