如何使用n个上下文管理器?

6

使用with语句,我们可以只缩进/嵌套一层,即可进入多个上下文处理器:

>>> from contextlib import contextmanager
>>> @contextmanager
... def frobnicate(n):
...     print('frobbing {}'.format(n))
...     yield
... 
>>> frob1 = frobnicate(1)
>>> frob2 = frobnicate(2)
>>> with frob1, frob2:
...     pass
... 
frobbing 1
frobbing 2

但是这似乎不起作用:

>>> frobs = [frobnicate(1), frobnicate(2)]
>>> with *frobs:
...     pass
# SyntaxError: invalid syntax

我们如何在不手动编写每个上下文管理器的情况下进入n个上下文管理器?

1个回答

8

Python 3.3+有contextlib.ExitStack

from contextlib import ExitStack

with ExitStack() as stack:
    contexts = [stack.enter_context(frobnicate(i)) for i in range(2)]
    ...

请参考contextlib2以将其回溯到旧版本的Python。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接