Comments in continuation lines

Question:

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?

Asked By: fedorqui

||

Answers:

I don’t see any solution except nesting the with:

with open('a.txt', 'w') as f1: #comment1
    with open('b.txt', 'w') as f2: #comment2
        print True
Answered By: Hugues Fontenelle

You can’t have comments and backslash for line continuation on the same line. You need to use some other strategy.

The most basic would be to adjust the comment text to place it e.g. before the relevant section. You could also document your intentions without comments at all by refactoring the code returning the context into a function or method with a descriptive name.

Answered By: Dag Høidahl

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.

Answered By: Serge Ballesta

You cannot combine end-of-line comment (#) and line continuation () on the same line.

I am not recommending this. — However, sometimes you can masquerade your comment as a string:

with open(('a', '# COMMENT THIS')[0]) as f1, 
     open(('b', '# COMMENT THAT')[0]) as f2:
    print(f1, f2)
Answered By: Petr Vepřek
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.