PEP8代码规范
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
PEP8代码规范
代码规范由IDE做出,像PyCharm
PEPs是Index of Python Enhancement Proposals的缩写,译为:Python增强建议书索引。
其中的PEP8是Style Guide for Python Code,译为:Python代码样式指南。
官⽅⽂档⼀直在更新维护,有需要时也请直接查阅官⽅⽂档。
仅选取了其中的部分内容,略有偏差处,还望⾃证。
Introduction
0 介绍
内有原⽂如下:
This style guide evolves over time as additional conventions are identified and past conventions are rendered obsolete by changes in the language itself.
Many projects have their own coding style guidelines. In the event of any conflicts, such project-specific guides take precedence for that project.
译为:
这种风格指南随着时间的推移⽽逐渐演变,随着语⾔本⾝的变化,过去的约定也被淘汰了。
许多项⽬都有⾃⼰的编码风格指南。
在发⽣任何冲突时,这种特定于项⽬的指南优先⽤于该项⽬。
A Foolish Consistency is the Hobgoblin of Little Minds
1 愚蠢的⼀致性就像没脑⼦的怪物
内有原⽂如下:
In particular: do not break backwards compatibility just to comply with this PEP!
译为:
特别是:不要为了遵守这个PEP⽽破坏向后兼容性!
注:向后兼容性(Backward Compatibility),计算机术语,⼜称作向下兼容(Downward Compatibility)。
在计算机中指在⼀个程序或者类库更新到较新的版本后,⽤旧的版本程序创建的⽂档或系统仍能被正常操作或使⽤,或在旧版本的类库的基础上开发的程序仍能正常编译运⾏的情况。
向下兼容可以使⽤户在进⾏软件或硬件升级时,⼚商不必为新设备或新平台从头开始编制应⽤程序,以前的程序在新的环境中任然有效。
为了考虑向后兼容会带来⼀些累赘,尤其是进⾏过较多升级后,如:python 3.0 便是放弃向下兼容的⼀个例⼦。
Code lay-out
2 代码布局
Indentation
2.1 缩进
内有原⽂如下:
Use 4 spaces per indentation level.
译为:
每级缩进使⽤ 4 个空格。
注:python使⽤缩进控制代码层次、逻辑、界定代码块,据传语⾔诞⽣原因和创⽴者不喜欢C的{}有关。
Tabs or Spaces?
2.2 使⽤制表符或者空格?
内有原⽂如下:
Spaces are the preferred indentation method.
译为:
空格是⾸选缩进⽅法。
注:python3中空格和制表符可以混⽤,但在python2中使⽤时会出现报错。
Maximum Line Length
2.3 ⾏的最⼤长度?
内有原⽂如下:
Limit all lines to a maximum of 79 characters.
The Python standard library is conservative and requires limiting lines to 79 characters (and docstrings/comments to 72).
译为:
限制所有⾏的最⼤长度为 79 个字符。
Python标准库采⽤了保守的理念,将每⾏限制在79个字符(⽂档字符串/注释,最多72个字符)。
Should a line break before or after a binary operator?
2.4 在⼆元运算符之前或之后应该换⾏吗?
内有原⽂如下:
In Python code, it is permissible to break before or after a binary operator, as long as the convention is consistent locally.
译为:
在Python代码中,只要约定在本地⼀致,就可以在⼆元运算符之前或之后中断。
注:⼆元运算(Binary operation)是作⽤于两个对象的运算,由两个元素形成第三个元素的⼀种规则。
加、乘、交、并,积及合成均属⼆元运算。
Blank Lines
2.5 空⾏
内有原⽂如下:
Surround top-level function and class definitions with two blank lines.
Method definitions inside a class are surrounded by a single blank line.
Extra blank lines may be used (sparingly) to separate groups of related functions. Blank lines may be omitted between a bunch of related one-liners (e.g. a set of dummy implementations).
Use blank lines in functions, sparingly, to indicate logical sections.
译为:
顶层函数和类之间使⽤两个空⾏。
类的⽅法之间使⽤⼀个空⾏。
可以使⽤额外的空⾏来分隔相关函数组。
在⼀系列相关的单⾏代码(例如⼀组形参)之间可以省略空⾏。
在函数中使⽤空⾏,以表⽰不同的逻辑部分。
注:dummy表⽰虚⽆的元素,没有实际空间,甚⾄连名字都可以没有,它只有联系上实元才有意义。
dummy implementations,虚拟实现,形参,哑元。
函数的形参⼜称“哑元”,实参⼜称“实元”。
也可以理解为编写时的是形参,调⽤时传⼊的就是实参。
Source File Encoding
2.6 源⽂件编码
内有原⽂如下:
Code in the core Python distribution should always use UTF-8 (or ASCII in Python 2).
Files using ASCII (in Python 2) or UTF-8 (in Python 3) should not have an encoding declaration.
译为:
在Python核⼼部分的代码应该使⽤UTF-8(或Python 2的ASCII)。
⽂件使⽤ASCII(Python 2)或UTF-8(Python 3)不应该有编码声明。
Imports
2.7 导⼊
内有原⽂如下:
Imports should usually be on separate lines
Imports are always put at the top of the file
Imports should be grouped in the following order:
1.standard library imports
2.related third party imports
3.local application/library specific imports
You should put a blank line between each group of imports.
Implicit relative imports should never be used and have been removed in Python 3.
译为:
导⼊通常是分开的
导⼊通常被放置在⽂件的顶部
导⼊应按以下顺序分组:
1.标准库的导⼊
2.相关第三⽅进⼝
3.本地应⽤程序/库特定导⼊
应该在每个导⼊组之间设置空⾏
不使⽤隐式相对导⼊,并且其已在Python 3中移除
Module level dunder names
2.8 模块级的双下划线名称
内有原⽂如下:
Module level "dunders" (i.e. names with two leading and two trailing underscores) such as __all__, __author__, __version__, etc. should be placed after the module docstring but before any import statements except from __future__ imports.
译为:
模块级的“双下划线名称”(即前后都具有两个下划线的名称)如 __all__,__author__,__version__等,应放在⽂档字符串之后,除
了__future__之外模块的导⼊之前。
注:Dunder (Double UNDERscore),是⼀个特殊的专有合成词。
String Quotes
3 字符串引号
内有原⽂如下:
In Python, single-quoted strings and double-quoted strings are the same.
译为:
在Python中,单引号字符串和双引号字符串是相同的。
Whitespace in Expression and Statements
4 表达式和语句中的空格
Pet Peeves
4.1 ⽆伤⼤雅的⼩问题
内有原⽂如下:
Avoid extraneous whitespace in the following situations:
●Immediately inside parentheses, brackets or braces.
●Between a trailing comma and a following close parenthesis.
●Immediately before a comma, semicolon, or colon.
●However, in a slice the colon acts like a binary operator, and should have equal amounts on either side (treating it as the operator with the lowest priority).
●Immediately before the open parenthesis that starts the argument list of a function call.
●Immediately before the open parenthesis that starts an indexing or slicing.
●More than one space around an assignment (or other) operator to align it with another.
译为:
在下列情况下,避免多余的空格:
●紧接着圆括号、⽅括号和花括号的内侧不加空格。
●逗号及后⾯的括号之间不加空格。
●逗号,分号或冒号之前不加空格。
●在⼀个切⽚中,冒号就像⼀个⼆进制运算符(把它当作优先级最低的运算符),在冒号两边都应该有相等的空格数量。
●函数调⽤参数列表的圆括号前不加空格。
●索引或切⽚的⽅括号前不加空格。
●在赋值(或其他)语句的运算符周围,不要为了对齐⽽使⽤多个空格。
Other Recommendations
4.2 其他建议
内有原⽂如下:
Avoid trailing whitespace anywhere.
Always surround these binary operators with a single space on either side: assignment (=), augmented assignment (+=, -= etc.), comparisons (==, <, >, !=, <>, <=, >=, in, not in, is, is not), Booleans (and, or, not).
If operators with different priorities are used, consider adding whitespace around the operators with the lowest priority(ies).
Don't use spaces around the = sign when used to indicate a keyword argument or a default parameter value.
Function annotations should use the normal rules for colons and always have spaces around the -> arrow if present.
When combining an argument annotation with a default value, use spaces around the = sign.
Compound statements (multiple statements on the same line) are generally discouraged.
While sometimes it's okay to put an if/for/while with a small body on the same line, never do this for multi-clause statements. Also avoid folding such long lines!
译为:
避免尾随空格的地⽅。
总是在这些⼆元运算符前后加⼀个空格:赋值(=),⾃增赋值(+=,-= 等等),⽐较(==,<,>,!=,<>,<=,>=,in,not in,is,is not),布尔运算(and,or,not)。
如果使⽤具有不同优先级的运算符,可以考虑在最低优先级的运算符两侧添加空格。
函数调⽤参数列表内的关键字参数或缺省参数的“=”前后不加空格。
如果存在功能注释时,应该使⽤正常的规则,如:冒号之后和“->”的前后。
当将参数注释与默认值同时出现时,在“=”的前后使⽤空格。
复合语句(在同⼀⾏上的多个语句)通常不允许使⽤。
通常情况下,⼀⾏代码包括⼀个⼩的if/for/while块,是可以的。
但是多⼦句绝不可以。
同样,需要避免折叠类似的长代码⾏!
When to use trailing commas
5 何时使⽤后⾯的逗号
内有原⽂如下:
Trailing commas are usually optional, except they are mandatory when making a tuple of one element (and in Python 2 they have semantics for the print statement).
When trailing commas are redundant, they are often helpful when a version control system is used, when a list of values, arguments or imported items is expected to be extended over time. The pattern is to put each value (etc.) on a line by itself, always adding a trailing comma, and add the close parenthesis/bracket/brace on the next line.
译为:
尾随逗号通常是可选的,除⾮它们在构成⼀个元素的元组时是强制性的(在Python 2中,它们对打印语句具有语义)。
当尾随逗号不是必须使⽤时,它们有利于版本控制系统的使⽤,如⼤量的值、参数或导⼊项将随着时间⽽扩展的情况。
模式是将每个值(等)放在⼀⾏上,总是添加⼀个尾随逗号,并紧接着在下⼀⾏添加圆括号/⽅括号/花括号。
注:python 2中打印语句的尾随逗号,具有打印不换⾏的语义,即之后⼀次的打印是接着上⼀⾏进⾏。
Comments
6 注释
内有原⽂如下:
Comments that contradict the code are worse than no comments. Always make a priority of keeping the comments up-to-date when the code changes!
Please write your comments in English, unless you are 120% sure that the code will never be read by people who don't speak your language.
译为:
与代码相悖的评论⽐没有注释更糟糕。
当代码更改时,始终要使注释也同步更新!
请⽤英语写注释,除⾮你120%确定这些代码永远不会被不懂你语⾔的⼈阅读。
Block Comments
6.1 块注释
内有原⽂如下:
Block comments generally apply to some (or all) code that follows them, and are indented to the same level as that code. Each line of a block comment starts with a # and a single space.
Paragraphs inside a block comment are separated by a line containing a single #.
译为:
块注释在⼀些(或全部)代码之前,并和代码缩进⼀致。
每⾏注释均以 # 开头,然后紧跟⼀个空格。
块注释内的段落使⽤仅含 # 的单⾏分隔。
Inline Comments
6.2 ⾏内注释
内有原⽂如下:
Use inline comments sparingly.
译为:
谨慎地使⽤内嵌注释。
Documentation Strings
6.3 ⽂档字符串
内有原⽂如下:
Conventions for writing good documentation strings (a.k.a. "docstrings") are immortalized in PEP 257.
译为:
编写良好的⽂档字符串(⼜名 "docstrings"),已在 PEP 257中进⾏了约定。
Naming Conventions
7 命名约定
内有原⽂如下:
The naming conventions of Python's library are a bit of a mess, so we'll never get this completely consistent -- nevertheless, here are the currently recommended naming standards. New modules and packages (including third party frameworks) should be written to these standards, but where an existing library has a different style, internal consistency is preferred.
译为:
Python库的命名约定有点乱,所以我们从未达成完全⼀致。
但是,⽬前有⼀些推荐的标准。
新的模块和包(包括第三⽅框架)应该⽤这些标准,但是拥有不同风格的固有库,还是保持内部统⼀更好。
Overriding Principle
7.1 最重要的原则
内有原⽂如下:
Names that are visible to the user as public parts of the API should follow conventions that reflect usage rather than implementation.
译为:
作为API的公共部分可见名称的使⽤者,应遵循反映使⽤⽽⾮实现的约定。
Descriptive: Naming Styles
7.2 命名风格
内有原⽂如下:
There are a lot of different naming styles. It helps to be able to recognize what naming style is being used, independently from what they are used for.
译为:
有许多不同的命名风格。
它能够识别正在使⽤什么样的命名风格,⽽不考虑他们为什么使⽤。
Prescriptive: Naming Conventions
7.3 说明:命名规范
Names to Avoid
7.3.1 避免使⽤的名字
内有原⽂如下:
Never use the characters 'l' (lowercase letter el), 'O' (uppercase letter oh), or 'I' (uppercase letter eye) as single character variable names. In some fonts, these characters are indistinguishable from the numerals one and zero. When tempted to use 'l', use 'L' instead.
译为:
永远不要使⽤ 'l'(⼩写的L),'O'(⼤写的O),或者'I'(⼤写的I)作为单字变量名。
在某些字体中,这些字很难和数字的0 和 1 区分。
当打算⽤'l'的时候,⽤'L'来代替。
ASCII Compatibility
7.3.2 ASCII兼容
内有原⽂如下:
Identifiers used in the standard library must be ASCII compatible as described in the policy section of PEP 3131.
译为:
标准库中使⽤的标识符必须是ASCII兼容的,如PEP 3131的中描述的那样。
Package and Module Names
7.3.3 包和模块名称
内有原⽂如下:
Modules should have short, all-lowercase names. Underscores can be used in the module name if it improves readability. Python packages should also have short, all-lowercase names, although the use of underscores is discouraged.
When an extension module written in C or C++ has an accompanying Python module that provides a higher level (e.g. more object oriented) interface, the C/C++ module has a leading underscore (e.g. _socket).
译为:
模块应该⽤简短的,全⼩写的名字。
如果能增强可读性的话,可以使⽤下划线。
Python的包也要⽤全⼩写的,短名称,但是不建议⽤下划线。
当⽤C或C++连编写⼀个含有Python模块提供更⾼层(⽐如,更加⾯向对象)接⼝的扩展模块时,这个C/C++模块要有⼀个前导下划
线(如 _socket)。
Class Names
7.3.4 类名
内有原⽂如下:
Class names should normally use the CapWords convention.
译为:
毫⽆例外,类名要⽤⾸字母⼤写的规则。
Type variable names
7.3.5 类型的变量名
内有原⽂如下:
Names of type variables introduced in PEP 484 should normally use CapWords preferring short names: T, AnyStr, Num. It is recommended to add suffixes _co or _contra to the variables used to declare covariant or contravariant behavior correspondingly.
译为:
类型变量引⼊PEP 484规则,⼀般应使⽤⾸字母⼤写,并宁愿短名称,如: T, AnyStr, Num。
建议添加后缀_co或_contra⽤来声明协变或逆变⾏为相应的变量。
Exception Names
7.3.6 异常名
内有原⽂如下:
Because exceptions should be classes, the class naming convention applies here. However, you should use the suffix "Error" on your exception names (if the exception actually is an error).
译为:
异常也是类,所以这⾥也⽤类名规则。
但是,你异常名应该增加后缀 "Error"(如果你的异常确实是个错误的话)。
Global Variable Names
7.3.7 全局变量名
内有原⽂如下:
(Let's hope that these variables are meant for use inside one module only.) The conventions are about the same as those for functions. Modules that are designed for use via from M import * should use the __all__ mechanism to prevent exporting globals, or use the older convention of prefixing such globals with an underscore (which you might want to do to indicate these globals are "module non-public").译为:
(我们希望这些变量只在模块内部使⽤。
)这些规则和函数规则⼀样。
被设计为通过from M import *导⼊的模块。
应该⽤__all__机制来防⽌导出全局。
或者使⽤过去的全局变量前置下划线的规则(这是为了说明这些变量是"模块私有的")。
Function and variable names
7.3.8 函数名
内有原⽂如下:
Function names should be lowercase, with words separated by underscores as necessary to improve readability.
Variable names follow the same convention as function names.
mixedCase is allowed only in contexts where that's already the prevailing style (e.g. threading.py), to retain backwards compatibility.
译为:
函数名应该⽤⼩写,为了增加可读性可以⽤下划线分隔。
变量名与函数名遵循相同的约定。
⼤⼩写混合仅在为了兼容原有⼤⼩写混合风格占主体的情况下使⽤(⽐如 threading.py)。
Function and method arguments
7.3.9 函数和⽅法参数
内有原⽂如下:
Always use self for the first argument to instance methods.
Always use cls for the first argument to class methods.
If a function argument's name clashes with a reserved keyword, it is generally better to append a single trailing underscore rather than use an abbreviation or spelling corruption. Thus class_ is better than clss. (Perhaps better is to avoid such clashes by using a synonym.)
译为:
始终⽤self作为实例⽅法的第⼀个参数。
始终⽤cls作为类⽅法的第⼀个参数。
如果函数的参数名和保留字冲突。
⽤结尾下划线⽐缩写或是滥⽤的组词更好。
因此 class_ ⽐ clss好。
(也许,更好的避免冲突的⽅式是⽤同义词。
)
Method Names and Instance Variables
7.3.10 ⽅法名和实例变量
内有原⽂如下:
Use the function naming rules: lowercase with words separated by underscores as necessary to improve readability.
Use one leading underscore only for non-public methods and instance variables.
译为:
使⽤函数命名规则:使⽤下划线分隔的⼩写字母会提⾼可读性。
使⽤前导双下划线调⽤Python的名字变化规则来避免与⼦类中的名字冲突。
Constants
7.3.11 常量
内有原⽂如下:
Constants are usually defined on a module level and written in all capital letters with underscores separating words. Examples include MAX_OVERFLOW and TOTAL.
译为:
常量通常在模块级别中定义,⽤全⼤写和下划线分隔的字符来编写。
例如MAX_OVERFLOW 和 TOTAL。
Designing for inheritance
7.3.12 继承设计
内有原⽂如下:
We don't use the term "private" here, since no attribute is really private in Python (without a generally unnecessary amount of work).
If your class is intended to be subclassed, and you have attributes that you do not want subclasses to use, consider naming them with double leading underscores and no trailing underscores. This invokes Python's name mangling algorithm, where the name of the class is mangled into the attribute name. This helps avoid attribute name collisions should subclasses inadvertently contain attributes with the same name.
译为:
在这⾥我们没有使⽤术语"private",因为在Python并没有真正的私有属性(为了避免⼤量不必要的常规⼯作)。
如果你的类打算⽤来继承的话,并且你的属性不希望⼦类继承,那么考虑⽤双下划线开头,不要有结尾下划线。
这样会调⽤ Python的"名称变化术"算法,它会把类的名字错位成属性名。
这样可以帮助我们避免在⼦类中不⼩⼼包含了相同的名字造成的冲突。
Public and internal interfaces
7.4 公共和内部接⼝
内有原⽂如下:
Any backwards compatibility guarantees apply only to public interfaces. Accordingly, it is important that users be able to clearly distinguish between public and internal interfaces.
Documented interfaces are considered public, unless the documentation explicitly declares them to be provisional or internal interfaces exempt from the usual backwards compatibility guarantees. All undocumented interfaces should be assumed to be internal.
To better support introspection, modules should explicitly declare the names in their public API using the __all__ attribute. Setting __all__ to an empty list indicates that the module has no public API.
Even with __all__ set appropriately, internal interfaces (packages, modules, classes, functions, attributes or other names) should still be prefixed with a single leading underscore.
An interface is also considered internal if any containing namespace (package, module or class) is considered internal.
译为:
任何向后兼容性保证仅适⽤于公共接⼝。
因此,重要的是⽤户能够清楚地区分公共接⼝和内部接⼝。
⽂档化的接⼝被认为是公开的,除⾮⽂档明确声明它们是临时或内部接⼝,不受通常的向后兼容性保证。
所有未记录的接⼝都应该是内部的。
为了更好地⽀持反省,模块应该显式声明的名字在他们的公共API的使⽤__all__属性。
__all__设置为⼀个空列表表⽰模块没有公共API。
即使__all__适当设置,内部接⼝(封装、模块、类、函数、属性或其他名称)仍应以⼀个前导下划线。
如果任何包含命名空间(包、模块或类)被认为是内部的,则接⼝也被认为是内部的。
Programming Recommendations
8 编程建议
内有原⽂如下:
Code should be written in a way that does not disadvantage other implementations of Python (PyPy, Jython, IronPython, Cython, Psyco, and such).
Comparisons to singletons like None should always be done with is or is not, never the equality operators.
Use is not operator rather than not ... is. While both expressions are functionally identical, the former is more readable and preferred.
When implementing ordering operations with rich comparisons, it is best to implement all six operations (__eq__, __ne__, __lt__, __le__, __gt__, __ge__) rather than relying on other code to only exercise a particular comparison.
Always use a def statement instead of an assignment statement that binds a lambda expression directly to an identifier.
Derive exceptions from Exception rather than BaseException.
Use exception chaining appropriately. In Python 3, "raise X from Y" should be used to indicate explicit replacement without losing the original traceback.
When raising an exception in Python 2, use raise ValueError('message') instead of the older form raise ValueError, 'message'.
When catching exceptions, mention specific exceptions whenever possible instead of using a bare except: clause.
When binding caught exceptions to a name, prefer the explicit name binding syntax added in Python 2.6.
When catching operating system errors, prefer the explicit exception hierarchy introduced in Python 3.3 over introspection of errno values. Additionally, for all try/except clauses, limit the try clause to the absolute minimum amount of code necessary. Again, this avoids masking bugs.
When a resource is local to a particular section of code, use a with statement to ensure it is cleaned up promptly and reliably after use. A try/finally statement is also acceptable.
Context managers should be invoked through separate functions or methods whenever they do something other than acquire and release resources.
Be consistent in return statements.
Use string methods instead of the string module.
Use ''.startswith() and ''.endswith() instead of string slicing to check for prefixes or suffixes.
Object type comparisons should always use isinstance() instead of comparing types directly.
For sequences, (strings, lists, tuples), use the fact that empty sequences are false.
Don't write string literals that rely on significant trailing whitespace.
Don't compare boolean values to True or False using ==.
译为:
代码应该⽤不损害其他Python实现的⽅式去编写(如PyPy, Jython, IronPython, Cython, Psyco 等)
与诸如None这样的字符⽐较时,要使⽤“is”或“is not”,不要⽤“==”。
使⽤“is not”操作符,虽然“not ... is”在功能上完全相同,但前者更易于阅读和更受欢迎。
当⽤复杂⽐较实现排序操作时,最好去实现全部六个操作(__eq__, __ne__, __lt__, __le__, __gt__, __ge__),⽽不是依靠其他的代码去实现⼀些怪异的⽐较。
使⽤def语句,⽽不是直接将lambda表达式绑定到标识符的赋值语句。
从常规错误的基类中捕获异常,⽽不是从所有异常的基类中进⾏。
适当使⽤异常链。
在Python 3中,应该使⽤“raise X from Y”来表⽰显式替换且其不会丢失原始回溯。
当在Python 2中抛出⼀个异常时,使⽤“ raise ValueError('message')” 代替旧的“raise ValueError, 'message'”。
在捕获异常时,尽可能要⽤详细的异常声明,⽽不是使⽤⼀个空的“ except: ”⼦句。
当绑定捕捉到名称的异常时,请使⽤Python 2.6中添加的显式名称绑定语法。
当捕捉操作系统错误,优先使⽤在Python 3.3中引⼊的“errno”值反省以明确异常的层次结构。
此外,对于所有“try...except”语句,将“try”⼦句限制为最⼩的代码范围。
同样,这避免了掩盖错误。
当某个特定代码段的某个资源处于局部状态时,使⽤⼀个“with”语句确保它在使⽤之后迅速⽽可靠地被清除。
⼀个“try...finally”语句的也是可以接受的。
⽆论何时获取和释放资源,都应该通过单独的函数或⽅法调⽤上下⽂管理器。
返回语句是⼀致的。
使⽤字符串⽅法⽽不是字符串模块。
使⽤''.startswith() 和 ''.endswith()⽽⾮字符切⽚去检测前缀或后缀。
对象类型⽐较要⽤ isinstance() ⽽⾮直接⽐较。
对于序列(strings, lists, tuples),有效利⽤空序列为False这⼀技巧。
在字符串后不要有⼤量空格。
不⽤“==”进⾏布尔值的True 或 False ⽐较。
注:Exception-常规错误的基类,BaseException-所有异常的基类。
Python所有的错误都是从BaseException类派⽣的。
使⽤“try...except”语句⽤来检测try语句块中的错误,从⽽让except语句捕获异常信息并处理。
Function Annotations
8.1 函数注解
内有原⽂如下:
In order to be forward compatible, function annotations in Python 3 code should preferably use PEP 484 syntax.
The experimentation with annotation styles that was recommended previously in this PEP is no longer encouraged.
However, outside the stdlib, experiments within the rules of PEP 484 are now encouraged.
The Python standard library should be conservative in adopting such annotations, but their use is allowed for new code and for big refactorings.
For code that wants to make a different use of function annotations it is recommended to put a comment of the form.
Like linters, type checkers are optional, separate tools.
Users who don't want to use type checkers are free to ignore them.
For code that needs to be backwards compatible, type annotations can be added in the form of comments.
译为:
为了向前兼容,Python 3代码中的函数注释最好使⽤PEP 484语法。
先前在PEP中推荐的注释样式的实验不再受到⿎励。
在PEP 484规定试验正在⿎励。
Python标准库应该采⽤这种保守的注释,但它们允许使⽤新的代码和⼤的重构。
对于希望对函数注释作不同⽤途的代码,建议对表单进⾏注释。
像编码规范检查插件、类型检查器是可选的,单独的⼯具。
不希望使⽤类型检查器的⽤户可以忽略它们。
对于需要向后兼容的代码,可以以注释的形式添加类型注释。
注:linter-pep8是根据python的代码规范pep8⽽编写的插件,可以帮助python开发⼈员维护代码规范。
Variable annotations
8.2 变量注解
内有原⽂如下:
Annotations for module level variables, class and instance variables, and local variables should have a single space after the colon.
There should be no space before the colon.
If an assignment has a right hand side, then the equality sign should have exactly one space on both sides.
Although the PEP 526 is accepted for Python 3.6, the variable annotation syntax is the preferred syntax for stub files on all versions of Python.
译为:
对模块级变量、类和实例变量以及本地变量的注释应该在冒号之后有⼀个空格。
冒号前应该没有空格。
如果赋值的右边有⼀个空格,那么等号应该两边都有⼀个空格。
尽管对Python 3.6接受了PEP 526,但是变量注释语法是Python所有版本的存根⽂件的⾸选语法。
References
9 引⽤
[1] , Style Guide for C Code, van Rossum
[3] Donald Knuth's The TeXBook, pages 195 and 196.
Copyright
10 版权
内有原⽂如下:
This document has been placed in the public domain.
译为:
这份⽂件已经放在公共领域了。