PEP 8 Recommendations
Indentation
When the conditional part of an if-statement is long enough to require that it be written across multiple lines, it's worth noting that the combination of a two character keyword (i.e. if), plus a single space, plus an opening parenthesis creates a natural 4-space indent for the subsequent lines of the multiline conditional. This can produce a visual conflict with the indented suite of code nested inside the if-statement, which would also naturally be indented to 4 spaces. The PEP 8 takes no explicit position on how (or whether) to further visually distinguish such conditional lines from the nested suite inside the if-statement. Acceptable options in this situation include, but are not limited to:
# No extra indentation.
if (this_is_one_thing and
that_is_another_thing):
do_something()
# Add a comment, which will provide some distinction in editors
# supporting syntax highlighting.
if (this_is_one_thing and
that_is_another_thing):
# Since both conditions are true, we can do something.
do_something()
# Add some extra indentation on the conditional continuation
# line.
if (this_is_one_thing
and that_is_another_thing):
do_something()Compound Statements
Compound statements (multiple statements on the same line) are generally discouraged.
While sometimes it's okay to put an if with a small body on the same line, never do this for multi-clause statements. Also avoid folding such long lines!
Comparisons to singletons
Comparisons to singletons like
Noneshould always be done withisoris not, never the equality operators.Beware of writing
if xwhen you really meanif x is not None- e.g. when testing whether a variable or argument that defaults toNonewas set to some other value. The other value might have a type (such as a container) that could be false in a boolean context!Use
is notoperator rather thannot ... is. While both expressions are functionally identical, the former is more readable and preferred.
Last updated