gpt4 book ai didi

Python递归RuntimeError

转载 作者:太空狗 更新时间:2023-10-29 20:58:52 24 4
gpt4 key购买 nike

def f1():
f1()

我们都知道在Python中调用这个函数会产生RuntimeError: maximum recursion depth exceeded

我写了它的轻微修改版本:

def f2():
try:
f2() #This line throws an error
finally: #except works too
f2() #This line does not throw an error!

第二个函数永远运行,不会抛出 RuntimeError。更重要的是,我无法用 CtrlC 组合来阻止它。

我不明白为什么调用 f2() 不会抛出 RuntimeError。你能解释一下吗?

最佳答案

随着堆栈填满,它会在 try 中调用 f2,直到达到最大递归深度。

一旦到达那个位置,它就会引发一个 RuntimeError,它由 finally 处理

这又会引发相同的 RuntimeError,但现在会引发更早的堆栈,该堆栈会传递给 finally 调用。

在那里,它再次超过了最大深度。

当引发KeyboardInterrupt 时,程序将继续finally,并且不会退出。

从技术上讲,它不会永远运行下去,因为只有一个 finally。也就是说,(多亏了评论)它允许成倍增加的调用,这非常接近无穷大。 100 的递归深度将变成 2100 == 1267650600228229401496703205376。

如果每次调用需要 1 毫秒,则需要 4650 亿年 才能完成。这只是 100 的深度

关于Python递归RuntimeError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22972422/

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