Consider this example:
import math
import sys
sys.setrecursionlimit(100)
max_items = 10
def foo(ls):
if -(len(ls) // -max_items) >= sys.getrecursionlimit():
raise ValueError("List is too long. You'll hit the recusion limit")
ls, ls_ = ls[:max_items], ls[max_items:]
print(len(ls_))
if len(ls_) > 0:
foo(ls_)
foo(list(range(970)))
I would expect that my logic for raising a ValueError before the recursion limit is reached is correct. That is, I’m calculating the total number of times foo would need to be called (including the initial call) to process the list, and checking if that is equal to or above the recursion limit.
But for some reason even calling foo(list(range(970))) raises RecursionError: maximum recursion depth exceeded while calling a Python object. Maybe I’m not understanding what the argument of setrecursionlimit is?
EDIT: I had the recursion limit as 5 before but that’s not working on many people’s machines so I changed it to be much higher to avoid confusion about what the source of the error is.
>Solution :
Despite its name, the so-called "recursion limit" is not a limit on the number of recursive calls, but on the number of function calls.
This includes:
- your 97 recursive calls;
- plus the
printorlencalls inside your deepest recursive call; - plus whatever calls you made before your first recursive call, for instance to a
mainfunction; - plus possibly a small number of "invisible" calls made by the interpreter on top of the calls you made explicitly in your code.