I was testing stuff when I noticed that python's recursion limit doesn't seem to apply equally to all functions. I'm not sure why or how and couldn't find any documentation explaining this behavior.
Can someone explain this weird behavior to me? Or at least send me in the right direction?
The Code:
import sys
import inspect
LIMIT = sys.getrecursionlimit()
print(f"recursive limit is: {LIMIT}")
def get_max_lvl(lvl=0):
try:
return get_max_lvl(lvl=lvl + 1)
except RecursionError:
return lvl
def get_max_lvl_inspect(lvl=0):
try:
return get_max_lvl_inspect(lvl=lvl + 1)
except RecursionError:
print(f"stack level: {len(inspect.stack())}")
return lvl
def get_max_lvl_other(lvl=0):
try:
return get_max_lvl_other(lvl=lvl + 1)
except RecursionError:
print("blah")
return lvl
I ran the following in a shell:
$ python -i rec.py
recursive limit is: 1000
>>> get_max_lvl()
998
>>> get_max_lvl_inspect()
stack level: 983
981
>>> get_max_lvl_other()
blah
blah
994
And tried it the other way around in case it was due to the order:
$ python -i rec.py
recursive limit is: 1000
>>> get_max_lvl_other()
blah
blah
994
>>> get_max_lvl_inspect()
stack level: 983
981
>>> get_max_lvl()
998
But the function outputs seem consistent.
What is going on here?
getrecursionlimitis misleading. It's not a recursion stack, it's a call stack. All function calls are stacked, not just recursive calls.