问题描述
我做了一个小函数来实际测量最大递归限制:
I've made a small function that will actually measure the max recursion limit:
def f(x):
r = x
try:
r = f(x+1)
except Exception as e:
print(e)
finally:
return r
要知道会发生什么,我已经检查过:
To know what to expect I've checked:
In [28]: import sys
In [29]: sys.getrecursionlimit()
Out[29]: 1000
不过
In [30]: f(0)
maximum recursion depth exceeded
Out[30]: 970
这个数字不是固定的,总是在 ~970 左右,并且在不同的 python 实例之间略有变化(例如,从 spyder 到系统 cmd 提示符).
The number is not fixed, always around ~970, and slightly changes between different instances of python (e.g. from within spyder to system cmd prompt).
请注意,我在 python3 上使用 ipython.
Please note that I'm using ipython on python3.
这是怎么回事?为什么我得到的实际限制低于 sys.getrecursionlimit()
值?
What's going on? Why is the actual limit I'm getting lower than the sys.getrecursionlimit()
value?
推荐答案
递归限制不是递归的限制,而是python解释器堆栈的最大深度.在你的函数执行之前,堆栈上有一些东西.Spyder 会在调用您的脚本之前执行一些 Python 内容,就像 ipython 等其他解释器一样.
The recursion limit is not the limit on recursion but the maximum depth of the python interpreter stack.There is something on the stack before your function gets executed. Spyder executes some python stuff before it calls your script, as do other interpreters like ipython.
您可以通过 inspect
模块中的方法检查堆栈.
You can inspect the stack via methods in the inspect
module.
在我的 CPython 中:
In CPython for me:
>>>print(len(inspect.stack()))
1
在我的 Ipython 中:
In Ipython for me:
>>>print(len(inspect.stack()))
10
正如 knbk 在评论中指出的,一旦您达到堆栈限制,就会抛出 RecursionError 并且解释器会稍微提高堆栈限制,以便您可以优雅地处理错误.如果你也用尽了那个限制,python 就会崩溃.
As knbk pointed out in the comments as soon as you hit the stack limit a RecursionError is thrown and the interpreter raises the stack limit a bit to give you a possibility to handle the error gracefully. If you also exhaust that limit python will crash.
这篇关于最大递归并不完全是 sys.getrecursionlimit() 所声称的.怎么来的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!