Why Python raises RecursionError before it exceeds the real recursion limit?

柔情痞子 提交于 2020-12-29 07:29:05

问题


So I was trying to play with sys.getrecursionlimit() and sys.setrecursionlimit() methods. By default recursion limit was 3000.

I tried to check it using this code:

def recursive(n):
    print(n)
    recursive(n+1)
recursive(0)

It does print the numbers to 2979, it delays for a second, prints 2980 and then raises the RecursionError

RecursionError: maximum recursion depth exceeded while calling a Python object

I know that error should be raised when it exceeds recursion limit that sys.getrecursionlimit() returns, but it doesn't

Seems like it always doing it 20times before the recursion limit

I also tried this:

sys.setrecursionlimit(100)
def recursive(n):
    print(n)
    recursive(n+1)
recursive(0)

It still does the same thing, prints all the numbers to 79, delays for a second, prints 80 and then raises the very same error

Why it does raise the error before it exceeds the real recursion limit that we set or get by sys.getrecursionlimit() ?


回答1:


There's stuff on the stack before you called your function.

In this case, it seems the call stack was already 20 calls deep before you called recursive.

See here for how to analyze the stack if you're really curious what's making up those 20 calls.




回答2:


Your recursive() function is not the only component that counts towards the limit. Some Python internals also increase the counter, because Python code can cause them to be called multiple times too. The print() function is one of them.

Bottom line is that the recursion limit doesn't only apply to the Python functions you wrote. It applies to the whole call stack.




回答3:


Actually, the recursive function "ALONE" is invoked exactly max=3000 number of times as long as you remove the "print" function. This is because python built-in functions also contribute to the limit.

import sys
count = 0
def recursive(n):
    global count
    count = count + 1
    recursive(n+1)


sys.setrecursionlimit(3000)
try:
    recursive(0)
except:
    print count  # would print 2999


来源:https://stackoverflow.com/questions/55560258/why-python-raises-recursionerror-before-it-exceeds-the-real-recursion-limit

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!