我知道with
语句在同一级别上支持多个上下文管理器,如下所示:
with open('foo.txt') as foo, open('bar.txt') as bar:
do_something()
但是如果上下文管理器列表对于一行来说太长了怎么办?例如:
with open('foo.txt') as foo, open('bar.txt') as bar, open('bla.txt') as bla, open('yada.txt') as yada:
do_something()
当前,这些是Python 3.7中的无效语法:
with (
open('foo.txt') as foo,
open('bar.txt') as bar,
open('bla.txt') as bla,
open('yada.txt') as yada, # same thing without the last trailing comma
):
do_something()
with
open('foo.txt') as foo,
open('bar.txt') as bar,
open('bla.txt') as bla,
open('yada.txt') as yada, # same thing without the last trailing comma
:
do_something()
我可以做到:
foo = open('foo.txt')
bar = open('bar.txt')
bla = open('bla.txt')
yada = open('yada.txt')
with foo, bar, bla, yada:
do_something()
但是随着我添加更多的上下文管理器,即使增长的时间也会太长。
我也可以这样做:
with open('foo.txt') as foo:
with open('bar.txt' as bar:
with open('bla.txt' as bla:
with open('yada.txt') as yada:
do_something()
但这很丑。它还缺乏对人类读者的语义提示。我们之所以要首先将多个上下文管理器放在同一级别上,是有原因的。
我知道很多上下文管理器属于同一级别是非常罕见的,但这绝对是可能的。
答案 0 :(得分:1)
续行是您的朋友在这里...
with \
open('foo.txt') as foo, \
open('bar.txt') as bar, \
open('bla.txt') as bla, \
open('yada.txt') as yada \
:
do_something()
这实际上在PEP-8中有专门提及。