gpt4 book ai didi

python - 在 python 中抛出 GeneratorExit 和调用 close() 之间的区别

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

感谢您提出我的问题。我试着把我的问题说清楚,但如果因为我的英语还有不清楚的地方,请告诉我。

我正在研究 Python 协同程序,并且读到在生成器上调用 close() 方法类似于将 GeneratorExit 扔给生成器。所以我尝试如下。

def gen(n):
while True:
yield n

test = gen(10)
next(test)
test.throw(GeneratorExit)

然后发生GeneratorExit异常。然而,当我尝试 test.close() 时,它没有引发任何异常。

所以我稍微修改了上面的代码;

def gen(n):
while True:
try:
yield n
except GeneratorExit:
break
test = gen(10)
next(test)
test.throw(GeneratorExit)

由于处理了 GeneratorExit,它没有被引发,但是发生了 StopIteration 异常。我知道如果没有更多 yield ,StopIteration 异常就会出现。但是,当我使用修改后的代码再次尝试 test.close() 时,它没有被引发。

你能告诉我抛出 GeneratorExit 和调用 close() 方法有什么区别吗?

更准确地说,我可以理解为什么 test.throw(GeneratorExit) 会出现 StopIterationGeneratorExit 异常,但我不知道为什么在使用 test.close()

时不会引发这些异常

谢谢。

最佳答案

GeneratorExit 发生在以下两种情况之一:

  • 当你调用 close
  • 当 python 调用该生成器的垃圾收集器时。

(参见 documentation)

你可以在下面的代码中看到:

def gen(n):
while True:
try:
yield n
except GeneratorExit:
print("gen caught a GeneratorExit exception")
break # (throws a StopIteration exception)

def gen_rte(n):
while True:
try:
yield n
except GeneratorExit:
print("gen_rte caught a GeneratorExit exception")
# No break here - we'll get a runtime exception

test = gen(10)
print(next(test))
==> 10

test.close()
==> gen caught a GeneratorExit exception


test = gen(15)
print(next(test))
==> 15
test.throw(GeneratorExit)

==> gen 捕获了 GeneratorExit 异常 追溯(最近一次通话): 文件“...”,第 20 行,位于 测试抛出(GeneratorExit) StopIteration(这是'break'语句的结果

test = gen_rte(20)
print(next(test))
==> 20

test.close()
==>
gen_rte caught a GeneratorExit exception
Traceback (most recent call last):
File "...", line 24, in <module>
test.close()
RuntimeError: generator ignored GeneratorExit

最后,在程序结束之前还有另一个 GeneratorExit 异常 - 我相信这是垃圾收集器的结果。 gen_rte 捕获到 GeneratorExit 异常 异常被忽略: RuntimeError:生成器忽略了 GeneratorExit

关于python - 在 python 中抛出 GeneratorExit 和调用 close() 之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62241212/

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