我有一堆要链接的上下文管理器.乍一看,contextlib.nested看起来很合适.但是,该方法在文档中被标记为已弃用,该文档还指出,最新的with语句可直接允许这样做:
Deprecated since version 2.7: The with-statement now supports this
functionality directly (without the confusing error prone quirks).
但是我无法让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)