首页 > 解决方案 > 我在哪里可以看到为从递归限制中恢复而保留的“额外递归”堆栈的数量?

问题描述

这个问题是关于尝试理解 python 内部的。

考虑代码:

import sys

sys.setrecursionlimit(100)

def myfunc(n):
    print(n, sys.getrecursionlimit())
    try:
        myfunc(n+1)
    except Exception as e1:
        print('Cannot proceed')
        print(e1)
        try:
            myfunc(n+1)
        except Exception as e2:
            print('That went wrong')
            print(e2)

myfunc(0)

警告 - 此代码用于 python 内部研究并导致 python 崩溃。导致实际Fatal Python error: Cannot recover from stack overflow.

这是结果:

....
....
92 100
93 100
94 100
95 100
Cannot proceed
maximum recursion depth exceeded while calling a Python object
95 100
96 100
97 100
98 100
99 100
100 100
101 100
102 100
103 100
104 100
105 100
106 100
107 100
108 100
109 100
110 100
111 100
112 100
113 100
114 100
115 100
116 100
117 100
118 100
119 100
120 100
121 100
122 100
123 100
124 100
125 100
126 100
127 100
128 100
129 100
130 100
131 100
132 100
133 100
134 100
135 100
136 100
137 100
138 100
139 100
140 100
141 100
142 100
143 100
144 100
Fatal Python error: Cannot recover from stack overflow.

Current thread 0x0000379c (most recent call first):
  File "....test.py", line 7 in myfunc
  File "....test.py", line 9 in myfunc
....
....

这是我想象的大致情况:

  1. 在达到递归限制之前,该函数会一直计数到接近 100。接近 100 而不是 100,因为 python 本身使用了一些堆栈。
  2. 当异常发生时,实际递归限制设置得更高以允许恢复。
  3. 由于我的函数坚持不断进行递归,它会在一段时间后达到新的限制。
  4. 但这一次,这种“扩展限制”恢复机制被耗尽,发生了致命的堆栈溢出。

我对吗?

我的问题:我可以使用等效的东西查看某些系统变量中的“额外递归”堆栈的数量sys.getrecursionlimit()吗?

标签: pythonrecursioninternals

解决方案


推荐阅读