How to __enter__ n context managers?

问题描述 投票:0回答:1

使用 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 上下文管理器而不必手动写出每个上下文管理器?

python with-statement contextmanager
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 版本。

© www.soinside.com 2019 - 2024. All rights reserved.