续行中的注释

Comments in continuation lines

假设我有一个多行命令:

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

if 块中,我可以在其中一个条件旁边添加注释,方法是使用括号将行括起来:

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

而且,事实上,它与 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.

但是,有时您需要使用延续。例如,long, multiple with-statements cannot use implicit continuation。那么,如何在特定行旁边添加注释呢?这不起作用:

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

更一般地说,是否有一种通用方法可以在特定续行旁边添加注释?

除了嵌套 with:

我没有看到任何解决方案
with open('a.txt', 'w') as f1: #comment1
    with open('b.txt', 'w') as f2: #comment2
        print True

您不能在同一行上为续行添加注释和反斜杠。您需要使用其他策略。

最基本的是调整评论文本以放置它,例如在相关部分之前。您还可以通过将返回上下文的代码重构为具有描述性名称的函数或方法来记录您的意图,而无需注释。

你不能。从 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

因此参考手册明确不允许在显式续行中添加注释。

您不能在同一行中合并行尾注释 (#) 和续行 (\)。

我不推荐这个。 -- 但是,有时您可以将您的评论伪装成字符串:

with open(('a', '# COMMENT THIS')[0]) as f1, \
     open(('b', '# COMMENT THAT')[0]) as f2:
    print(f1, f2)