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:
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
None
should always be done withis
oris not
, never the equality operators.Beware of writing
if x
when you really meanif x is not None
- e.g. when testing whether a variable or argument that defaults toNone
was 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 not
operator rather thannot ... is
. While both expressions are functionally identical, the former is more readable and preferred.
Last updated