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?
This is because the
inspect.stackfunction, theprintfunction and thelenfunction all add some frames to the call stack, reducing the space available for recursion depth.So the more you use those functions, the less space can work with.
get_max_lvl: Not calling these functions -> maximum recursion depthget_max_lvl_other: Just calling print -> recursion depth lower than 1.get_max_lvl_inspect: calling all three functions -> recursion depth lower than 2.