with是否可以在 Python 中使用语句声明多个变量?
with
就像是:
from __future__ import with_statement with open("out.txt","wt"), open("in.txt") as file_out, file_in: for line in file_in: file_out.write(line)
…或者是同时清理两个资源的问题?
从 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__()方法引发了异常。
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)
从 Python 3.10 开始,您可以使用括号:
with ( A() as a, B(a) as b, C(a, b) as c, ): doSomething(a, c)