从v3.1和
Python 2.7开始,在Python
3中是可能的。新
with语法支持多个上下文管理器:
with A() as a, B() as b, C() as c: doSomething(a,b,c)
与相比
contextlib.nested,即使或方法引发了异常,这也保证
a并
b会
__exit__()调用
C()的
__enter__()。
您也可以在较新的定义中使用较早的变量(以下为h / t
Ahmad):
with A() as a, B(a) as b, C(a, b) as c: doSomething(a, c)



