我有一堆想要链接的上下文管理器。乍一看,contextlib.nested
看起来像是一个合适的解决方案。但是,此方法在文档中被标记为已弃用,该文档还指出最新的 with
语句允许直接执行此操作:
但是我无法让 Python 3.4.3 使用上下文管理器的动态迭代:
class Foo():
def __enter__(self):
print('entering:', self.name)
return self
def __exit__(self, *_):
pass
def __init__(self, name):
self.name = name
foo = Foo('foo')
bar = Foo('bar')
是否链式:
from itertools import chain
m = chain([foo], [bar])
with m:
pass
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: __exit__
m = [foo, bar]
直接提供列表:
with m:
pass
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: __exit__
或开箱:
with (*m):
pass
File "<stdin>", line 1
SyntaxError: can use starred expression only as assignment target
那么,如何正确地在
with
语句中正确链接动态数量的上下文管理器? 最佳答案
你误解了那条线。 with
语句需要多个上下文管理器,用逗号分隔,但不是可迭代的:
with foo, bar:
作品。
如果您需要支持一组动态的上下文管理器,请使用
contextlib.ExitStack()
object:from contextlib import ExitStack
with ExitStack() as stack:
for cm in (foo, bar):
stack.enter_context(cm)
关于python - 将上下文管理器的动态迭代链接到单个 with 语句,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30981706/