是否可以使用A声明多个变量with
python的声明?
就像是:
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 3和Python 2.7。新的with
句法支持多个上下文经理:
with A() as a, B() as b, C() as c:
doSomething(a,b,c)
不像contextlib.nested
,这保证了a
和b
会有他们的__exit__()
即使C()
或者是__enter__()
方法提出了例外。
您还可以在以后的定义中使用早期变量(H/T艾哈迈德以下):
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)