在Python中,创建多行with
语句的一种清晰方式是什么?我想在单个with
语句中打开多个文件,但是这段代码过长,我希望将其分成多行。像这样:
class Dummy:
def __enter__(self): pass
def __exit__(self, type, value, traceback): pass
with Dummy() as a, Dummy() as b,
Dummy() as c:
pass
很遗憾,那是一个SyntaxError
。所以我尝试了这个:
with (Dummy() as a, Dummy() as b,
Dummy() as c):
pass
也是一个语法错误。不过,这个可以工作:
with Dummy() as a, Dummy() as b,\
Dummy() as c:
pass
但是如果我想添加一条评论呢?这样是不起作用的:
with Dummy() as a, Dummy() as b,\
# my comment explaining why I wanted Dummy() as c\
Dummy() as c:
pass
也没有明显的变化可以放置 \
。
有没有一种干净的方式来创建一个允许在其中添加注释的多行 with
语句?
with
语句中使用\
进行行续,因为您无法使用隐式续行。然而,如果您想内联注释,这并不能真正帮助您的情况。 - Eric Appelt