In general, the recursion limit is a wonderful thing to catch accidental infinite recursion and prevent it from blowing the stack. However occasionally I have had to write heavily recursive code and so I resorted to putting warnings in documentation / docstrings informing users that they may need to manually set the recursion limit to something bigger or have added at the top of a script / module / library something like:
import sys
sys.setrecursionlimit(1_000_000) # Set this higher if needed
Since sys.setrecursionlimit(limit)
already requires that limit
is a positive integer, I suggest having a special value of limit
(for example 0
, -1
or even just any negative number`) which bypasses the recursion checks. Of course the dangers that come with bypassing these checks (for example crashing Python) would need to be very explicitly documented.
In the case of CPython, adding this bypass involves changing ~20 lines. Most of which follow the pattern of switching:
if (++st->recursion_depth > st->recursion_limit) {
to:
if (++st->recursion_depth > st->recursion_limit && st->recursion_limit > 0)
I’ve tried this out and was able to quickly make a branch in which all current tests pass.