PEP 8: Add green and red sidbar for good and bad examples (#3567)
This commit is contained in:
parent
0e298a1903
commit
d341072725
|
@ -148,6 +148,16 @@ pre {
|
||||||
white-space: pre;
|
white-space: pre;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.good pre {
|
||||||
|
border-left: 3px solid rgba(74, 182, 93, 1);
|
||||||
|
}
|
||||||
|
.bad pre {
|
||||||
|
border-left: 3px solid rgb(244, 76, 78);
|
||||||
|
}
|
||||||
|
.maybe pre {
|
||||||
|
border-left: 3px solid rgb(244, 227, 76);
|
||||||
|
}
|
||||||
|
|
||||||
/* Contents rules */
|
/* Contents rules */
|
||||||
details > summary {
|
details > summary {
|
||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
|
|
|
@ -1,13 +1,10 @@
|
||||||
PEP: 8
|
PEP: 8
|
||||||
Title: Style Guide for Python Code
|
Title: Style Guide for Python Code
|
||||||
Version: $Revision$
|
|
||||||
Last-Modified: $Date$
|
|
||||||
Author: Guido van Rossum <guido@python.org>,
|
Author: Guido van Rossum <guido@python.org>,
|
||||||
Barry Warsaw <barry@python.org>,
|
Barry Warsaw <barry@python.org>,
|
||||||
Alyssa Coghlan <ncoghlan@gmail.com>
|
Alyssa Coghlan <ncoghlan@gmail.com>
|
||||||
Status: Active
|
Status: Active
|
||||||
Type: Process
|
Type: Process
|
||||||
Content-Type: text/x-rst
|
|
||||||
Created: 05-Jul-2001
|
Created: 05-Jul-2001
|
||||||
Post-History: 05-Jul-2001, 01-Aug-2013
|
Post-History: 05-Jul-2001, 01-Aug-2013
|
||||||
|
|
||||||
|
@ -81,7 +78,10 @@ using Python's implicit line joining inside parentheses, brackets and
|
||||||
braces, or using a *hanging indent* [#fn-hi]_. When using a hanging
|
braces, or using a *hanging indent* [#fn-hi]_. When using a hanging
|
||||||
indent the following should be considered; there should be no
|
indent the following should be considered; there should be no
|
||||||
arguments on the first line and further indentation should be used to
|
arguments on the first line and further indentation should be used to
|
||||||
clearly distinguish itself as a continuation line::
|
clearly distinguish itself as a continuation line:
|
||||||
|
|
||||||
|
.. code-block::
|
||||||
|
:class: good
|
||||||
|
|
||||||
# Correct:
|
# Correct:
|
||||||
|
|
||||||
|
@ -100,7 +100,8 @@ clearly distinguish itself as a continuation line::
|
||||||
var_one, var_two,
|
var_one, var_two,
|
||||||
var_three, var_four)
|
var_three, var_four)
|
||||||
|
|
||||||
::
|
.. code-block::
|
||||||
|
:class: bad
|
||||||
|
|
||||||
# Wrong:
|
# Wrong:
|
||||||
|
|
||||||
|
@ -116,7 +117,10 @@ clearly distinguish itself as a continuation line::
|
||||||
|
|
||||||
The 4-space rule is optional for continuation lines.
|
The 4-space rule is optional for continuation lines.
|
||||||
|
|
||||||
Optional::
|
Optional:
|
||||||
|
|
||||||
|
.. code-block::
|
||||||
|
:class: good
|
||||||
|
|
||||||
# Hanging indents *may* be indented to other than 4 spaces.
|
# Hanging indents *may* be indented to other than 4 spaces.
|
||||||
foo = long_function_name(
|
foo = long_function_name(
|
||||||
|
@ -134,7 +138,10 @@ conflict with the indented suite of code nested inside the ``if``-statement,
|
||||||
which would also naturally be indented to 4 spaces. This PEP takes no
|
which would also naturally be indented to 4 spaces. This PEP takes no
|
||||||
explicit position on how (or whether) to further visually distinguish such
|
explicit position on how (or whether) to further visually distinguish such
|
||||||
conditional lines from the nested suite inside the ``if``-statement.
|
conditional lines from the nested suite inside the ``if``-statement.
|
||||||
Acceptable options in this situation include, but are not limited to::
|
Acceptable options in this situation include, but are not limited to:
|
||||||
|
|
||||||
|
.. code-block::
|
||||||
|
:class: good
|
||||||
|
|
||||||
# No extra indentation.
|
# No extra indentation.
|
||||||
if (this_is_one_thing and
|
if (this_is_one_thing and
|
||||||
|
@ -158,7 +165,10 @@ operators below.)
|
||||||
|
|
||||||
The closing brace/bracket/parenthesis on multiline constructs may
|
The closing brace/bracket/parenthesis on multiline constructs may
|
||||||
either line up under the first non-whitespace character of the last
|
either line up under the first non-whitespace character of the last
|
||||||
line of list, as in::
|
line of list, as in:
|
||||||
|
|
||||||
|
.. code-block::
|
||||||
|
:class: good
|
||||||
|
|
||||||
my_list = [
|
my_list = [
|
||||||
1, 2, 3,
|
1, 2, 3,
|
||||||
|
@ -170,7 +180,10 @@ line of list, as in::
|
||||||
)
|
)
|
||||||
|
|
||||||
or it may be lined up under the first character of the line that
|
or it may be lined up under the first character of the line that
|
||||||
starts the multiline construct, as in::
|
starts the multiline construct, as in:
|
||||||
|
|
||||||
|
.. code-block::
|
||||||
|
:class: good
|
||||||
|
|
||||||
my_list = [
|
my_list = [
|
||||||
1, 2, 3,
|
1, 2, 3,
|
||||||
|
@ -228,7 +241,10 @@ for line continuation.
|
||||||
|
|
||||||
Backslashes may still be appropriate at times. For example, long,
|
Backslashes may still be appropriate at times. For example, long,
|
||||||
multiple ``with``-statements could not use implicit continuation
|
multiple ``with``-statements could not use implicit continuation
|
||||||
before Python 3.10, so backslashes were acceptable for that case::
|
before Python 3.10, so backslashes were acceptable for that case:
|
||||||
|
|
||||||
|
.. code-block::
|
||||||
|
:class: maybe
|
||||||
|
|
||||||
with open('/path/to/some/file/you/want/to/read') as file_1, \
|
with open('/path/to/some/file/you/want/to/read') as file_1, \
|
||||||
open('/path/to/some/file/being/written', 'w') as file_2:
|
open('/path/to/some/file/being/written', 'w') as file_2:
|
||||||
|
@ -249,7 +265,10 @@ But this can hurt readability in two ways: the operators tend to get
|
||||||
scattered across different columns on the screen, and each operator is
|
scattered across different columns on the screen, and each operator is
|
||||||
moved away from its operand and onto the previous line. Here, the eye
|
moved away from its operand and onto the previous line. Here, the eye
|
||||||
has to do extra work to tell which items are added and which are
|
has to do extra work to tell which items are added and which are
|
||||||
subtracted::
|
subtracted:
|
||||||
|
|
||||||
|
.. code-block::
|
||||||
|
:class: bad
|
||||||
|
|
||||||
# Wrong:
|
# Wrong:
|
||||||
# operators sit far away from their operands
|
# operators sit far away from their operands
|
||||||
|
@ -266,7 +285,10 @@ within a paragraph always break after binary operations and relations,
|
||||||
displayed formulas always break before binary operations" [3]_.
|
displayed formulas always break before binary operations" [3]_.
|
||||||
|
|
||||||
Following the tradition from mathematics usually results in more
|
Following the tradition from mathematics usually results in more
|
||||||
readable code::
|
readable code:
|
||||||
|
|
||||||
|
.. code-block::
|
||||||
|
:class: good
|
||||||
|
|
||||||
# Correct:
|
# Correct:
|
||||||
# easy to match operators with operands
|
# easy to match operators with operands
|
||||||
|
@ -324,19 +346,26 @@ similar policy.
|
||||||
Imports
|
Imports
|
||||||
-------
|
-------
|
||||||
|
|
||||||
- Imports should usually be on separate lines::
|
- Imports should usually be on separate lines:
|
||||||
|
|
||||||
|
.. code-block::
|
||||||
|
:class: good
|
||||||
|
|
||||||
# Correct:
|
# Correct:
|
||||||
import os
|
import os
|
||||||
import sys
|
import sys
|
||||||
|
|
||||||
::
|
.. code-block::
|
||||||
|
:class: bad
|
||||||
|
|
||||||
# Wrong:
|
# Wrong:
|
||||||
import sys, os
|
import sys, os
|
||||||
|
|
||||||
|
|
||||||
It's okay to say this though::
|
It's okay to say this though:
|
||||||
|
|
||||||
|
.. code-block::
|
||||||
|
:class: good
|
||||||
|
|
||||||
# Correct:
|
# Correct:
|
||||||
from subprocess import Popen, PIPE
|
from subprocess import Popen, PIPE
|
||||||
|
@ -355,7 +384,10 @@ Imports
|
||||||
- Absolute imports are recommended, as they are usually more readable
|
- Absolute imports are recommended, as they are usually more readable
|
||||||
and tend to be better behaved (or at least give better error
|
and tend to be better behaved (or at least give better error
|
||||||
messages) if the import system is incorrectly configured (such as
|
messages) if the import system is incorrectly configured (such as
|
||||||
when a directory inside a package ends up on ``sys.path``)::
|
when a directory inside a package ends up on ``sys.path``):
|
||||||
|
|
||||||
|
.. code-block::
|
||||||
|
:class: good
|
||||||
|
|
||||||
import mypkg.sibling
|
import mypkg.sibling
|
||||||
from mypkg import sibling
|
from mypkg import sibling
|
||||||
|
@ -363,7 +395,10 @@ Imports
|
||||||
|
|
||||||
However, explicit relative imports are an acceptable alternative to
|
However, explicit relative imports are an acceptable alternative to
|
||||||
absolute imports, especially when dealing with complex package layouts
|
absolute imports, especially when dealing with complex package layouts
|
||||||
where using absolute imports would be unnecessarily verbose::
|
where using absolute imports would be unnecessarily verbose:
|
||||||
|
|
||||||
|
.. code-block::
|
||||||
|
:class: good
|
||||||
|
|
||||||
from . import sibling
|
from . import sibling
|
||||||
from .sibling import example
|
from .sibling import example
|
||||||
|
@ -372,17 +407,23 @@ Imports
|
||||||
use absolute imports.
|
use absolute imports.
|
||||||
|
|
||||||
- When importing a class from a class-containing module, it's usually
|
- When importing a class from a class-containing module, it's usually
|
||||||
okay to spell this::
|
okay to spell this:
|
||||||
|
|
||||||
|
.. code-block::
|
||||||
|
:class: good
|
||||||
|
|
||||||
from myclass import MyClass
|
from myclass import MyClass
|
||||||
from foo.bar.yourclass import YourClass
|
from foo.bar.yourclass import YourClass
|
||||||
|
|
||||||
If this spelling causes local name clashes, then spell them explicitly::
|
If this spelling causes local name clashes, then spell them explicitly:
|
||||||
|
|
||||||
|
.. code-block::
|
||||||
|
:class: good
|
||||||
|
|
||||||
import myclass
|
import myclass
|
||||||
import foo.bar.yourclass
|
import foo.bar.yourclass
|
||||||
|
|
||||||
and use "myclass.MyClass" and "foo.bar.yourclass.YourClass".
|
and use ``myclass.MyClass`` and ``foo.bar.yourclass.YourClass``.
|
||||||
|
|
||||||
- Wildcard imports (``from <module> import *``) should be avoided, as
|
- Wildcard imports (``from <module> import *``) should be avoided, as
|
||||||
they make it unclear which names are present in the namespace,
|
they make it unclear which names are present in the namespace,
|
||||||
|
@ -404,7 +445,10 @@ underscores) such as ``__all__``, ``__author__``, ``__version__``,
|
||||||
etc. should be placed after the module docstring but before any import
|
etc. should be placed after the module docstring but before any import
|
||||||
statements *except* ``from __future__`` imports. Python mandates that
|
statements *except* ``from __future__`` imports. Python mandates that
|
||||||
future-imports must appear in the module before any other code except
|
future-imports must appear in the module before any other code except
|
||||||
docstrings::
|
docstrings:
|
||||||
|
|
||||||
|
.. code-block::
|
||||||
|
:class: good
|
||||||
|
|
||||||
"""This is the example module.
|
"""This is the example module.
|
||||||
|
|
||||||
|
@ -442,32 +486,45 @@ Pet Peeves
|
||||||
|
|
||||||
Avoid extraneous whitespace in the following situations:
|
Avoid extraneous whitespace in the following situations:
|
||||||
|
|
||||||
- Immediately inside parentheses, brackets or braces::
|
- Immediately inside parentheses, brackets or braces:
|
||||||
|
|
||||||
|
.. code-block::
|
||||||
|
:class: good
|
||||||
|
|
||||||
# Correct:
|
# Correct:
|
||||||
spam(ham[1], {eggs: 2})
|
spam(ham[1], {eggs: 2})
|
||||||
|
|
||||||
::
|
.. code-block::
|
||||||
|
:class: bad
|
||||||
|
|
||||||
# Wrong:
|
# Wrong:
|
||||||
spam( ham[ 1 ], { eggs: 2 } )
|
spam( ham[ 1 ], { eggs: 2 } )
|
||||||
|
|
||||||
- Between a trailing comma and a following close parenthesis::
|
- Between a trailing comma and a following close parenthesis:
|
||||||
|
|
||||||
|
.. code-block::
|
||||||
|
:class: good
|
||||||
|
|
||||||
# Correct:
|
# Correct:
|
||||||
foo = (0,)
|
foo = (0,)
|
||||||
|
|
||||||
::
|
.. code-block::
|
||||||
|
:class: bad
|
||||||
|
|
||||||
# Wrong:
|
# Wrong:
|
||||||
bar = (0, )
|
bar = (0, )
|
||||||
|
|
||||||
- Immediately before a comma, semicolon, or colon::
|
- Immediately before a comma, semicolon, or colon:
|
||||||
|
|
||||||
|
.. code-block::
|
||||||
|
:class: good
|
||||||
|
|
||||||
# Correct:
|
# Correct:
|
||||||
if x == 4: print(x, y); x, y = y, x
|
if x == 4: print(x, y); x, y = y, x
|
||||||
|
|
||||||
::
|
|
||||||
|
.. code-block::
|
||||||
|
:class: bad
|
||||||
|
|
||||||
# Wrong:
|
# Wrong:
|
||||||
if x == 4 : print(x , y) ; x , y = y , x
|
if x == 4 : print(x , y) ; x , y = y , x
|
||||||
|
@ -476,7 +533,10 @@ Avoid extraneous whitespace in the following situations:
|
||||||
should have equal amounts on either side (treating it as the
|
should have equal amounts on either side (treating it as the
|
||||||
operator with the lowest priority). In an extended slice, both
|
operator with the lowest priority). In an extended slice, both
|
||||||
colons must have the same amount of spacing applied. Exception:
|
colons must have the same amount of spacing applied. Exception:
|
||||||
when a slice parameter is omitted, the space is omitted::
|
when a slice parameter is omitted, the space is omitted:
|
||||||
|
|
||||||
|
.. code-block::
|
||||||
|
:class: good
|
||||||
|
|
||||||
# Correct:
|
# Correct:
|
||||||
ham[1:9], ham[1:9:3], ham[:9:3], ham[1::3], ham[1:9:]
|
ham[1:9], ham[1:9:3], ham[:9:3], ham[1::3], ham[1:9:]
|
||||||
|
@ -485,7 +545,8 @@ Avoid extraneous whitespace in the following situations:
|
||||||
ham[: upper_fn(x) : step_fn(x)], ham[:: step_fn(x)]
|
ham[: upper_fn(x) : step_fn(x)], ham[:: step_fn(x)]
|
||||||
ham[lower + offset : upper + offset]
|
ham[lower + offset : upper + offset]
|
||||||
|
|
||||||
::
|
.. code-block::
|
||||||
|
:class: bad
|
||||||
|
|
||||||
# Wrong:
|
# Wrong:
|
||||||
ham[lower + offset:upper + offset]
|
ham[lower + offset:upper + offset]
|
||||||
|
@ -494,36 +555,48 @@ Avoid extraneous whitespace in the following situations:
|
||||||
ham[ : upper]
|
ham[ : upper]
|
||||||
|
|
||||||
- Immediately before the open parenthesis that starts the argument
|
- Immediately before the open parenthesis that starts the argument
|
||||||
list of a function call::
|
list of a function call:
|
||||||
|
|
||||||
|
.. code-block::
|
||||||
|
:class: good
|
||||||
|
|
||||||
# Correct:
|
# Correct:
|
||||||
spam(1)
|
spam(1)
|
||||||
|
|
||||||
::
|
.. code-block::
|
||||||
|
:class: bad
|
||||||
|
|
||||||
# Wrong:
|
# Wrong:
|
||||||
spam (1)
|
spam (1)
|
||||||
|
|
||||||
- Immediately before the open parenthesis that starts an indexing or
|
- Immediately before the open parenthesis that starts an indexing or
|
||||||
slicing::
|
slicing:
|
||||||
|
|
||||||
|
.. code-block::
|
||||||
|
:class: good
|
||||||
|
|
||||||
# Correct:
|
# Correct:
|
||||||
dct['key'] = lst[index]
|
dct['key'] = lst[index]
|
||||||
|
|
||||||
::
|
.. code-block::
|
||||||
|
:class: bad
|
||||||
|
|
||||||
# Wrong:
|
# Wrong:
|
||||||
dct ['key'] = lst [index]
|
dct ['key'] = lst [index]
|
||||||
|
|
||||||
- More than one space around an assignment (or other) operator to
|
- More than one space around an assignment (or other) operator to
|
||||||
align it with another::
|
align it with another:
|
||||||
|
|
||||||
|
.. code-block::
|
||||||
|
:class: good
|
||||||
|
|
||||||
# Correct:
|
# Correct:
|
||||||
x = 1
|
x = 1
|
||||||
y = 2
|
y = 2
|
||||||
long_variable = 3
|
long_variable = 3
|
||||||
|
|
||||||
::
|
.. code-block::
|
||||||
|
:class: bad
|
||||||
|
|
||||||
# Wrong:
|
# Wrong:
|
||||||
x = 1
|
x = 1
|
||||||
|
@ -549,7 +622,10 @@ Other Recommendations
|
||||||
whitespace around the operators with the lowest priority(ies). Use
|
whitespace around the operators with the lowest priority(ies). Use
|
||||||
your own judgment; however, never use more than one space, and
|
your own judgment; however, never use more than one space, and
|
||||||
always have the same amount of whitespace on both sides of a binary
|
always have the same amount of whitespace on both sides of a binary
|
||||||
operator::
|
operator:
|
||||||
|
|
||||||
|
.. code-block::
|
||||||
|
:class: good
|
||||||
|
|
||||||
# Correct:
|
# Correct:
|
||||||
i = i + 1
|
i = i + 1
|
||||||
|
@ -558,7 +634,8 @@ Other Recommendations
|
||||||
hypot2 = x*x + y*y
|
hypot2 = x*x + y*y
|
||||||
c = (a+b) * (a-b)
|
c = (a+b) * (a-b)
|
||||||
|
|
||||||
::
|
.. code-block::
|
||||||
|
:class: bad
|
||||||
|
|
||||||
# Wrong:
|
# Wrong:
|
||||||
i=i+1
|
i=i+1
|
||||||
|
@ -569,13 +646,17 @@ Other Recommendations
|
||||||
|
|
||||||
- Function annotations should use the normal rules for colons and
|
- Function annotations should use the normal rules for colons and
|
||||||
always have spaces around the ``->`` arrow if present. (See
|
always have spaces around the ``->`` arrow if present. (See
|
||||||
`Function Annotations`_ below for more about function annotations.)::
|
`Function Annotations`_ below for more about function annotations.):
|
||||||
|
|
||||||
|
.. code-block::
|
||||||
|
:class: good
|
||||||
|
|
||||||
# Correct:
|
# Correct:
|
||||||
def munge(input: AnyStr): ...
|
def munge(input: AnyStr): ...
|
||||||
def munge() -> PosInt: ...
|
def munge() -> PosInt: ...
|
||||||
|
|
||||||
::
|
.. code-block::
|
||||||
|
:class: bad
|
||||||
|
|
||||||
# Wrong:
|
# Wrong:
|
||||||
def munge(input:AnyStr): ...
|
def munge(input:AnyStr): ...
|
||||||
|
@ -583,13 +664,17 @@ Other Recommendations
|
||||||
|
|
||||||
- Don't use spaces around the ``=`` sign when used to indicate a
|
- Don't use spaces around the ``=`` sign when used to indicate a
|
||||||
keyword argument, or when used to indicate a default value for an
|
keyword argument, or when used to indicate a default value for an
|
||||||
*unannotated* function parameter::
|
*unannotated* function parameter:
|
||||||
|
|
||||||
|
.. code-block::
|
||||||
|
:class: good
|
||||||
|
|
||||||
# Correct:
|
# Correct:
|
||||||
def complex(real, imag=0.0):
|
def complex(real, imag=0.0):
|
||||||
return magic(r=real, i=imag)
|
return magic(r=real, i=imag)
|
||||||
|
|
||||||
::
|
.. code-block::
|
||||||
|
:class: bad
|
||||||
|
|
||||||
# Wrong:
|
# Wrong:
|
||||||
def complex(real, imag = 0.0):
|
def complex(real, imag = 0.0):
|
||||||
|
@ -597,20 +682,27 @@ Other Recommendations
|
||||||
|
|
||||||
|
|
||||||
When combining an argument annotation with a default value, however, do use
|
When combining an argument annotation with a default value, however, do use
|
||||||
spaces around the ``=`` sign::
|
spaces around the ``=`` sign:
|
||||||
|
|
||||||
|
.. code-block::
|
||||||
|
:class: good
|
||||||
|
|
||||||
# Correct:
|
# Correct:
|
||||||
def munge(sep: AnyStr = None): ...
|
def munge(sep: AnyStr = None): ...
|
||||||
def munge(input: AnyStr, sep: AnyStr = None, limit=1000): ...
|
def munge(input: AnyStr, sep: AnyStr = None, limit=1000): ...
|
||||||
|
|
||||||
::
|
.. code-block::
|
||||||
|
:class: bad
|
||||||
|
|
||||||
# Wrong:
|
# Wrong:
|
||||||
def munge(input: AnyStr=None): ...
|
def munge(input: AnyStr=None): ...
|
||||||
def munge(input: AnyStr, limit = 1000): ...
|
def munge(input: AnyStr, limit = 1000): ...
|
||||||
|
|
||||||
- Compound statements (multiple statements on the same line) are
|
- Compound statements (multiple statements on the same line) are
|
||||||
generally discouraged::
|
generally discouraged:
|
||||||
|
|
||||||
|
.. code-block::
|
||||||
|
:class: good
|
||||||
|
|
||||||
# Correct:
|
# Correct:
|
||||||
if foo == 'blah':
|
if foo == 'blah':
|
||||||
|
@ -619,7 +711,10 @@ Other Recommendations
|
||||||
do_two()
|
do_two()
|
||||||
do_three()
|
do_three()
|
||||||
|
|
||||||
Rather not::
|
Rather not:
|
||||||
|
|
||||||
|
.. code-block::
|
||||||
|
:class: bad
|
||||||
|
|
||||||
# Wrong:
|
# Wrong:
|
||||||
if foo == 'blah': do_blah_thing()
|
if foo == 'blah': do_blah_thing()
|
||||||
|
@ -629,14 +724,20 @@ Other Recommendations
|
||||||
on the same line, never do this for multi-clause statements. Also
|
on the same line, never do this for multi-clause statements. Also
|
||||||
avoid folding such long lines!
|
avoid folding such long lines!
|
||||||
|
|
||||||
Rather not::
|
Rather not:
|
||||||
|
|
||||||
|
.. code-block::
|
||||||
|
:class: bad
|
||||||
|
|
||||||
# Wrong:
|
# Wrong:
|
||||||
if foo == 'blah': do_blah_thing()
|
if foo == 'blah': do_blah_thing()
|
||||||
for x in lst: total += x
|
for x in lst: total += x
|
||||||
while t < 10: t = delay()
|
while t < 10: t = delay()
|
||||||
|
|
||||||
Definitely not::
|
Definitely not:
|
||||||
|
|
||||||
|
.. code-block::
|
||||||
|
:class: bad
|
||||||
|
|
||||||
# Wrong:
|
# Wrong:
|
||||||
if foo == 'blah': do_blah_thing()
|
if foo == 'blah': do_blah_thing()
|
||||||
|
@ -656,12 +757,16 @@ When to Use Trailing Commas
|
||||||
|
|
||||||
Trailing commas are usually optional, except they are mandatory when
|
Trailing commas are usually optional, except they are mandatory when
|
||||||
making a tuple of one element. For clarity, it is recommended to
|
making a tuple of one element. For clarity, it is recommended to
|
||||||
surround the latter in (technically redundant) parentheses::
|
surround the latter in (technically redundant) parentheses:
|
||||||
|
|
||||||
|
.. code-block::
|
||||||
|
:class: good
|
||||||
|
|
||||||
# Correct:
|
# Correct:
|
||||||
FILES = ('setup.cfg',)
|
FILES = ('setup.cfg',)
|
||||||
|
|
||||||
::
|
.. code-block::
|
||||||
|
:class: bad
|
||||||
|
|
||||||
# Wrong:
|
# Wrong:
|
||||||
FILES = 'setup.cfg',
|
FILES = 'setup.cfg',
|
||||||
|
@ -673,7 +778,10 @@ 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.
|
comma, and add the close parenthesis/bracket/brace on the next line.
|
||||||
However it does not make sense to have a trailing comma on the same
|
However it does not make sense to have a trailing comma on the same
|
||||||
line as the closing delimiter (except in the above case of singleton
|
line as the closing delimiter (except in the above case of singleton
|
||||||
tuples)::
|
tuples):
|
||||||
|
|
||||||
|
.. code-block::
|
||||||
|
:class: good
|
||||||
|
|
||||||
# Correct:
|
# Correct:
|
||||||
FILES = [
|
FILES = [
|
||||||
|
@ -684,7 +792,8 @@ tuples)::
|
||||||
error=True,
|
error=True,
|
||||||
)
|
)
|
||||||
|
|
||||||
::
|
.. code-block::
|
||||||
|
:class: bad
|
||||||
|
|
||||||
# Wrong:
|
# Wrong:
|
||||||
FILES = ['setup.cfg', 'tox.ini',]
|
FILES = ['setup.cfg', 'tox.ini',]
|
||||||
|
@ -736,11 +845,17 @@ Inline comments should be separated by at least two spaces from the
|
||||||
statement. They should start with a # and a single space.
|
statement. They should start with a # and a single space.
|
||||||
|
|
||||||
Inline comments are unnecessary and in fact distracting if they state
|
Inline comments are unnecessary and in fact distracting if they state
|
||||||
the obvious. Don't do this::
|
the obvious. Don't do this:
|
||||||
|
|
||||||
|
.. code-block::
|
||||||
|
:class: bad
|
||||||
|
|
||||||
x = x + 1 # Increment x
|
x = x + 1 # Increment x
|
||||||
|
|
||||||
But sometimes, this is useful::
|
But sometimes, this is useful:
|
||||||
|
|
||||||
|
.. code-block::
|
||||||
|
:class: good
|
||||||
|
|
||||||
x = x + 1 # Compensate for border
|
x = x + 1 # Compensate for border
|
||||||
|
|
||||||
|
@ -757,7 +872,11 @@ Conventions for writing good documentation strings
|
||||||
|
|
||||||
- :pep:`257` describes good docstring conventions. Note that most
|
- :pep:`257` describes good docstring conventions. Note that most
|
||||||
importantly, the ``"""`` that ends a multiline docstring should be
|
importantly, the ``"""`` that ends a multiline docstring should be
|
||||||
on a line by itself::
|
on a line by itself:
|
||||||
|
|
||||||
|
.. code-block::
|
||||||
|
:class: good
|
||||||
|
|
||||||
|
|
||||||
"""Return a foobang
|
"""Return a foobang
|
||||||
|
|
||||||
|
@ -765,7 +884,10 @@ Conventions for writing good documentation strings
|
||||||
"""
|
"""
|
||||||
|
|
||||||
- For one liner docstrings, please keep the closing ``"""`` on
|
- For one liner docstrings, please keep the closing ``"""`` on
|
||||||
the same line::
|
the same line:
|
||||||
|
|
||||||
|
.. code-block::
|
||||||
|
:class: good
|
||||||
|
|
||||||
"""Return an ex-parrot."""
|
"""Return an ex-parrot."""
|
||||||
|
|
||||||
|
@ -834,7 +956,10 @@ case convention):
|
||||||
with an underscore.
|
with an underscore.
|
||||||
|
|
||||||
- ``single_trailing_underscore_``: used by convention to avoid
|
- ``single_trailing_underscore_``: used by convention to avoid
|
||||||
conflicts with Python keyword, e.g. ::
|
conflicts with Python keyword, e.g. :
|
||||||
|
|
||||||
|
.. code-block::
|
||||||
|
:class: good
|
||||||
|
|
||||||
tkinter.Toplevel(master, class_='ClassName')
|
tkinter.Toplevel(master, class_='ClassName')
|
||||||
|
|
||||||
|
@ -899,7 +1024,10 @@ Type Variable Names
|
||||||
Names of type variables introduced in :pep:`484` should normally use CapWords
|
Names of type variables introduced in :pep:`484` should normally use CapWords
|
||||||
preferring short names: ``T``, ``AnyStr``, ``Num``. It is recommended to add
|
preferring short names: ``T``, ``AnyStr``, ``Num``. It is recommended to add
|
||||||
suffixes ``_co`` or ``_contra`` to the variables used to declare covariant
|
suffixes ``_co`` or ``_contra`` to the variables used to declare covariant
|
||||||
or contravariant behavior correspondingly::
|
or contravariant behavior correspondingly:
|
||||||
|
|
||||||
|
.. code-block::
|
||||||
|
:class: good
|
||||||
|
|
||||||
from typing import TypeVar
|
from typing import TypeVar
|
||||||
|
|
||||||
|
@ -1107,12 +1235,16 @@ Programming Recommendations
|
||||||
|
|
||||||
- Use ``is not`` operator rather than ``not ... is``. While both
|
- Use ``is not`` operator rather than ``not ... is``. While both
|
||||||
expressions are functionally identical, the former is more readable
|
expressions are functionally identical, the former is more readable
|
||||||
and preferred::
|
and preferred:
|
||||||
|
|
||||||
|
.. code-block::
|
||||||
|
:class: good
|
||||||
|
|
||||||
# Correct:
|
# Correct:
|
||||||
if foo is not None:
|
if foo is not None:
|
||||||
|
|
||||||
::
|
.. code-block::
|
||||||
|
:class: bad
|
||||||
|
|
||||||
# Wrong:
|
# Wrong:
|
||||||
if not foo is None:
|
if not foo is None:
|
||||||
|
@ -1134,12 +1266,16 @@ Programming Recommendations
|
||||||
that confusion doesn't arise in other contexts.
|
that confusion doesn't arise in other contexts.
|
||||||
|
|
||||||
- Always use a def statement instead of an assignment statement that binds
|
- Always use a def statement instead of an assignment statement that binds
|
||||||
a lambda expression directly to an identifier::
|
a lambda expression directly to an identifier:
|
||||||
|
|
||||||
|
.. code-block::
|
||||||
|
:class: good
|
||||||
|
|
||||||
# Correct:
|
# Correct:
|
||||||
def f(x): return 2*x
|
def f(x): return 2*x
|
||||||
|
|
||||||
::
|
.. code-block::
|
||||||
|
:class: bad
|
||||||
|
|
||||||
# Wrong:
|
# Wrong:
|
||||||
f = lambda x: 2*x
|
f = lambda x: 2*x
|
||||||
|
@ -1178,7 +1314,10 @@ Programming Recommendations
|
||||||
exception in the new exception message).
|
exception in the new exception message).
|
||||||
|
|
||||||
- When catching exceptions, mention specific exceptions whenever
|
- When catching exceptions, mention specific exceptions whenever
|
||||||
possible instead of using a bare ``except:`` clause::
|
possible instead of using a bare ``except:`` clause:
|
||||||
|
|
||||||
|
.. code-block::
|
||||||
|
:class: good
|
||||||
|
|
||||||
try:
|
try:
|
||||||
import platform_specific_module
|
import platform_specific_module
|
||||||
|
@ -1209,7 +1348,10 @@ Programming Recommendations
|
||||||
|
|
||||||
- Additionally, for all try/except clauses, limit the ``try`` clause
|
- Additionally, for all try/except clauses, limit the ``try`` clause
|
||||||
to the absolute minimum amount of code necessary. Again, this
|
to the absolute minimum amount of code necessary. Again, this
|
||||||
avoids masking bugs::
|
avoids masking bugs:
|
||||||
|
|
||||||
|
.. code-block::
|
||||||
|
:class: good
|
||||||
|
|
||||||
# Correct:
|
# Correct:
|
||||||
try:
|
try:
|
||||||
|
@ -1219,7 +1361,8 @@ Programming Recommendations
|
||||||
else:
|
else:
|
||||||
return handle_value(value)
|
return handle_value(value)
|
||||||
|
|
||||||
::
|
.. code-block::
|
||||||
|
:class: bad
|
||||||
|
|
||||||
# Wrong:
|
# Wrong:
|
||||||
try:
|
try:
|
||||||
|
@ -1234,13 +1377,17 @@ Programming Recommendations
|
||||||
after use. A try/finally statement is also acceptable.
|
after use. A try/finally statement is also acceptable.
|
||||||
|
|
||||||
- Context managers should be invoked through separate functions or methods
|
- Context managers should be invoked through separate functions or methods
|
||||||
whenever they do something other than acquire and release resources::
|
whenever they do something other than acquire and release resources:
|
||||||
|
|
||||||
|
.. code-block::
|
||||||
|
:class: good
|
||||||
|
|
||||||
# Correct:
|
# Correct:
|
||||||
with conn.begin_transaction():
|
with conn.begin_transaction():
|
||||||
do_stuff_in_transaction(conn)
|
do_stuff_in_transaction(conn)
|
||||||
|
|
||||||
::
|
.. code-block::
|
||||||
|
:class: bad
|
||||||
|
|
||||||
# Wrong:
|
# Wrong:
|
||||||
with conn:
|
with conn:
|
||||||
|
@ -1256,7 +1403,10 @@ Programming Recommendations
|
||||||
any return statement returns an expression, any return statements
|
any return statement returns an expression, any return statements
|
||||||
where no value is returned should explicitly state this as ``return
|
where no value is returned should explicitly state this as ``return
|
||||||
None``, and an explicit return statement should be present at the
|
None``, and an explicit return statement should be present at the
|
||||||
end of the function (if reachable)::
|
end of the function (if reachable):
|
||||||
|
|
||||||
|
.. code-block::
|
||||||
|
:class: good
|
||||||
|
|
||||||
# Correct:
|
# Correct:
|
||||||
|
|
||||||
|
@ -1271,7 +1421,8 @@ Programming Recommendations
|
||||||
return None
|
return None
|
||||||
return math.sqrt(x)
|
return math.sqrt(x)
|
||||||
|
|
||||||
::
|
.. code-block::
|
||||||
|
:class: bad
|
||||||
|
|
||||||
# Wrong:
|
# Wrong:
|
||||||
|
|
||||||
|
@ -1287,35 +1438,47 @@ Programming Recommendations
|
||||||
- Use ``''.startswith()`` and ``''.endswith()`` instead of string
|
- Use ``''.startswith()`` and ``''.endswith()`` instead of string
|
||||||
slicing to check for prefixes or suffixes.
|
slicing to check for prefixes or suffixes.
|
||||||
|
|
||||||
startswith() and endswith() are cleaner and less error prone::
|
startswith() and endswith() are cleaner and less error prone:
|
||||||
|
|
||||||
|
.. code-block::
|
||||||
|
:class: good
|
||||||
|
|
||||||
# Correct:
|
# Correct:
|
||||||
if foo.startswith('bar'):
|
if foo.startswith('bar'):
|
||||||
|
|
||||||
::
|
.. code-block::
|
||||||
|
:class: bad
|
||||||
|
|
||||||
# Wrong:
|
# Wrong:
|
||||||
if foo[:3] == 'bar':
|
if foo[:3] == 'bar':
|
||||||
|
|
||||||
- Object type comparisons should always use isinstance() instead of
|
- Object type comparisons should always use isinstance() instead of
|
||||||
comparing types directly::
|
comparing types directly:
|
||||||
|
|
||||||
|
.. code-block::
|
||||||
|
:class: good
|
||||||
|
|
||||||
# Correct:
|
# Correct:
|
||||||
if isinstance(obj, int):
|
if isinstance(obj, int):
|
||||||
|
|
||||||
::
|
.. code-block::
|
||||||
|
:class: bad
|
||||||
|
|
||||||
# Wrong:
|
# Wrong:
|
||||||
if type(obj) is type(1):
|
if type(obj) is type(1):
|
||||||
|
|
||||||
- For sequences, (strings, lists, tuples), use the fact that empty
|
- For sequences, (strings, lists, tuples), use the fact that empty
|
||||||
sequences are false::
|
sequences are false:
|
||||||
|
|
||||||
|
.. code-block::
|
||||||
|
:class: good
|
||||||
|
|
||||||
# Correct:
|
# Correct:
|
||||||
if not seq:
|
if not seq:
|
||||||
if seq:
|
if seq:
|
||||||
|
|
||||||
::
|
.. code-block::
|
||||||
|
:class: bad
|
||||||
|
|
||||||
# Wrong:
|
# Wrong:
|
||||||
if len(seq):
|
if len(seq):
|
||||||
|
@ -1325,17 +1488,24 @@ Programming Recommendations
|
||||||
whitespace. Such trailing whitespace is visually indistinguishable
|
whitespace. Such trailing whitespace is visually indistinguishable
|
||||||
and some editors (or more recently, reindent.py) will trim them.
|
and some editors (or more recently, reindent.py) will trim them.
|
||||||
|
|
||||||
- Don't compare boolean values to True or False using ``==``::
|
- Don't compare boolean values to True or False using ``==``:
|
||||||
|
|
||||||
|
.. code-block::
|
||||||
|
:class: good
|
||||||
|
|
||||||
# Correct:
|
# Correct:
|
||||||
if greeting:
|
if greeting:
|
||||||
|
|
||||||
::
|
.. code-block::
|
||||||
|
:class: bad
|
||||||
|
|
||||||
# Wrong:
|
# Wrong:
|
||||||
if greeting == True:
|
if greeting == True:
|
||||||
|
|
||||||
Worse::
|
Worse:
|
||||||
|
|
||||||
|
.. code-block::
|
||||||
|
:class: bad
|
||||||
|
|
||||||
# Wrong:
|
# Wrong:
|
||||||
if greeting is True:
|
if greeting is True:
|
||||||
|
@ -1344,7 +1514,10 @@ Programming Recommendations
|
||||||
within the finally suite of a ``try...finally``, where the flow control
|
within the finally suite of a ``try...finally``, where the flow control
|
||||||
statement would jump outside the finally suite, is discouraged. This
|
statement would jump outside the finally suite, is discouraged. This
|
||||||
is because such statements will implicitly cancel any active exception
|
is because such statements will implicitly cancel any active exception
|
||||||
that is propagating through the finally suite::
|
that is propagating through the finally suite:
|
||||||
|
|
||||||
|
.. code-block::
|
||||||
|
:class: bad
|
||||||
|
|
||||||
# Wrong:
|
# Wrong:
|
||||||
def foo():
|
def foo():
|
||||||
|
@ -1376,7 +1549,10 @@ annotations have changed.
|
||||||
refactorings.
|
refactorings.
|
||||||
|
|
||||||
- For code that wants to make a different use of function annotations
|
- For code that wants to make a different use of function annotations
|
||||||
it is recommended to put a comment of the form::
|
it is recommended to put a comment of the form:
|
||||||
|
|
||||||
|
.. code-block::
|
||||||
|
:class: good
|
||||||
|
|
||||||
# type: ignore
|
# type: ignore
|
||||||
|
|
||||||
|
@ -1409,7 +1585,10 @@ similar to those on function annotations described above:
|
||||||
- There should be no space before the colon.
|
- There should be no space before the colon.
|
||||||
|
|
||||||
- If an assignment has a right hand side, then the equality sign should have
|
- If an assignment has a right hand side, then the equality sign should have
|
||||||
exactly one space on both sides::
|
exactly one space on both sides:
|
||||||
|
|
||||||
|
.. code-block::
|
||||||
|
:class: good
|
||||||
|
|
||||||
# Correct:
|
# Correct:
|
||||||
|
|
||||||
|
@ -1419,7 +1598,8 @@ similar to those on function annotations described above:
|
||||||
coords: Tuple[int, int]
|
coords: Tuple[int, int]
|
||||||
label: str = '<unknown>'
|
label: str = '<unknown>'
|
||||||
|
|
||||||
::
|
.. code-block::
|
||||||
|
:class: bad
|
||||||
|
|
||||||
# Wrong:
|
# Wrong:
|
||||||
|
|
||||||
|
@ -1462,14 +1642,3 @@ Copyright
|
||||||
=========
|
=========
|
||||||
|
|
||||||
This document has been placed in the public domain.
|
This document has been placed in the public domain.
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
..
|
|
||||||
Local Variables:
|
|
||||||
mode: indented-text
|
|
||||||
indent-tabs-mode: nil
|
|
||||||
sentence-end-double-space: t
|
|
||||||
fill-column: 70
|
|
||||||
coding: utf-8
|
|
||||||
End:
|
|
||||||
|
|
Loading…
Reference in New Issue