在 Python 中将多个同级上下文管理器拆分为多行

Split multiple same-level context managers to multiple lines in Python

我知道 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()

但是很丑。它还缺少对人类的语义提示 reader。我们首先要将多个上下文管理器放在同一级别是有原因的。

我知道许多个上下文管理器属于同一级别的情况很少见,但这绝对是可能的。

续行是你的朋友...

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.

中有具体提到