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

时间:2018-11-15 22:53:09

标签: python python-3.x 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

2 个答案:

答案 0 :(得分:2)

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)

答案 1 :(得分:2)

使用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语句的多管理器形式(如Joran Beasley's answer所示就更简单了)