在 Python 'with' 语句中重用多个上下文

Reusing multiple contexts in Python 'with' statement

在Python3中我们可以在with语句中使用多个上下文。但是,如果不能在 with 语句中立即构造它们,是否可以输入多个上下文?有没有可能做这样的事情?

def files():
    return open('a.txt', 'w'), open('b.txt', 'w')

with files():
    pass

或者这样:

files = open('a.txt', 'w'), open('b.txt', 'w')
with files:
    pass
from contextlib import contextmanager

@contextmanager
def files():
    with open('a.txt', 'w') as f1, open('b.txt', 'w') as f2:
         yield f1,f2

也许吧?

with files() as (f1,f2):
     print(f1,f2)

使用 contextlib.ExitStack 的示例:

from contextlib import ExitStack

def files(stack, *args):
    return [stack.enter_context(open(f, "w")) for f in args]

with ExitStack() as stack:
    f1, f2 = files(stack, "a.txt", "b.txt")
    ...

或没有包装纸

with ExitStack() as stack:
    f1, f2 = [stack.enter_context(open(f, "w")) for f in ["a.txt", "b.txt"]]
    ...

但是,当你提前知道要打开多少个文件时(而且是少量文件),with语句的多管理器形式如更简单。