A few extra clarifications about multiline if and with statements. Also,

conform the multiline-if statement conditionals to other recommendations in
the PEP, i.e. that lines in a multiline conditional end with the binary
operator.
This commit is contained in:
Barry Warsaw 2014-08-17 12:24:10 -04:00
parent a240f27644
commit 422ebe6d79
1 changed files with 22 additions and 14 deletions

View File

@ -121,29 +121,34 @@ Optional::
var_one, var_two,
var_three, var_four)
This PEP explicitly takes no position on how (or whether) to further
visually distinguish continuation lines in the header from the nested suite
in an ``if`` statement, where the combination of a two character keyword, a
single space and an opening parenthesis creates a natural 4-space indent for
the expression in the header. Some acceptable options in this situation
include::
.. _`multiline if-statements`:
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. This PEP 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
and that):
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
and that):
if (this_is_one_thing and
that_is_another_thing):
# Since both conditions are true, we can frobnicate.
do_something()
# Add some extra indentation on the conditional continuation line.
if (this
and that):
if (this_is_one_thing
and that_is_another_thing):
do_something()
The closing brace/bracket/parenthesis on multi-line constructs may
@ -231,9 +236,12 @@ multiple ``with``-statements cannot use implicit continuation, so
backslashes are acceptable::
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:
file_2.write(file_1.read())
(See the previous discussion on `multiline if-statements`_ for further
thoughts on the indentation of such multiline ``with``-statements.)
Another such case is with ``assert`` statements.
Make sure to indent the continued line appropriately. The preferred