gpt4 book ai didi

python - with-block 中多个 __exit__ 调用的顺序是否总是确定的?

转载 作者:行者123 更新时间:2023-12-04 12:09:07 24 4
gpt4 key购买 nike

鉴于以下 ContextManager类,这里是 __exit__ 的顺序以下示例中的调用 - 声明的相反顺序。
有趣的是,__exit__可以多次调用。这在 2.7 的所有 Python 版本中都是确定性的吗?如果没有,来自 哪个版本这个顺序是否可靠确定?

a = A()
b = B()
c = C()

with a, b, c, a, a:
print("Start")

测试线束
from typing import ContextManager

class A(ContextManager):
def __exit__(self, __exc_type, __exc_value, __traceback):
print("A exit")

class B(ContextManager):
def __exit__(self, __exc_type, __exc_value, __traceback):
print("B exit")

class C(ContextManager):
def __exit__(self, __exc_type, __exc_value, __traceback):
print("C exit")

a = A()
b = B()
c = C()

with a, b, c, a, a:
print("Start")
Python 3.7+ 输出:
Start
A exit
A exit
C exit
B exit
A exit

最佳答案

同一个 with 上的多个上下文管理器行被处理,就好像它们是嵌套的一样。所以这:

with a, b, c:
stuff()
相当于:
with a:
with b:
with c:
stuff()
也就是说, __enter__方法从左到右调用,当块结束时, __exit__方法被称为从右到左。

关于python - with-block 中多个 __exit__ 调用的顺序是否总是确定的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68248141/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com