Search code examples
pythoncontinuation

Comments in continuation lines


Say I have a multiline command:

if 2>1 \
 and 3>2:
    print True

In an if block, I can add a comment next to one of the conditions by using parentheses to wrap the lines:

if (2>1 #my comment
 and 3>2):
    print True

And, in fact, it is aligned with the recommened way of doing this by PEP 8 guideline:

The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces. Long lines can be broken over multiple lines by wrapping expressions in parentheses. These should be used in preference to using a backslash for line continuation.

However, sometimes you need to use continuations. For example, long, multiple with-statements cannot use implicit continuation. Then, how can I add a comment next to a specific line? This does not work:

with open('a') as f1, #my comment\
 open('b') as f2:
    print True

More generally, is there a generic way to add a comment next to a specific continuation line?


Solution

  • You cannot. Find some extracts from Python reference manual (3.4):

    A comment starts with a hash character (#) that is not part of a string literal, and ends at the end of the physical line.

    A line ending in a backslash cannot carry a comment

    A comment signifies the end of the logical line unless the implicit line joining rules are invoked

    Implicit line joining : Expressions in parentheses, square brackets or curly braces can be split over more than one physical line without using backslashes

    Implicitly continued lines can carry comments

    So the reference manual explicitly disallows to add a comment in an explicit continuation line.