PEP8代码规范(转载)

代码规范由IDE做出,像PyCharm

 

PEPs是Index of Python Enhancement Proposals的缩写,译为:Python增强建议书索引。

官方目录:https://www.python.org/dev/peps/

其中的PEP8是Style Guide for Python Code,译为:Python代码样式指南。

官方文档:https://www.python.org/dev/peps/pep-0008/

官方文档一直在更新维护,有需要时也请直接查阅官方文档。

仅选取了其中的部分内容,略有偏差处,还望自证。

 

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] PEP 7, Style Guide for C Code, van Rossum

[2] Barry's GNU Mailman style guide http://barry.warsaw.us/software/STYLEGUIDE.txt

[3] Donald Knuth's The TeXBook, pages 195 and 196.

[4] http://www.wikipedia.com/wiki/CamelCase

[5] Typeshed repo https://github.com/python/typeshed

[6] Suggested syntax for Python 2.7 and straddling code https://www.python.org/dev/peps/pep-0484/#suggested-syntax-for-python-2-7-and-straddling-code

 

 

Copyright

10 版权

内有原文如下:

  This document has been placed in the public domain.

译为:

  这份文件已经放在公共领域了。

 

 

原文地址:https://www.cnblogs.com/asreg/articles/9607790.html

 

posted @ 2021-12-07 17:31  吾言!  阅读(256)  评论(0编辑  收藏  举报