0

Is there a way I can measure how close I am to python's recursion limit? I know about sys.getrecursionlimit and sys.setrecursionlimit. I'd like to know how close I am to the limit, without actually reaching it: either by measuring the remaining gap, or by measuring how deep I am already and subtracting that from sys.getrecursionlimit(). If necessary, I suppose I could write a function that probes this by calling itself repeatedly until RecursionError and returning a counter, but is there a less messy way?

Bill Evans at Mariposa
  • 3,590
  • 1
  • 18
  • 22
  • 4
    Practically speaking, if you have to ask this question, you're way too close, and you should think about a way to write your code that doesn't involve arbitrarily deep recursion. That said, have you looked at the `inspect` module? That provides tools for inspecting the call stack so you could probably put something together with that. – Samwise Apr 02 '23 at 18:02
  • 3
    Excellent comment from @Samwise. If an algorithm goes anywhere near that limit, you should replace your algorithm. Maybe show what your programming problem is and look for ideas from others? – ProfDFrancis Apr 02 '23 at 18:06
  • @KellyBundy Given that OP knows how to determine the limit, "how do I find the depth?" is a perfectly serviceable duplicate of "how do I find (the limit - the depth)?" – Karl Knechtel Apr 02 '23 at 18:45
  • @Samwise: In general, your advice is good. But my program isn't executing an algorithm in a vacuum; it's observing a (rather perverse) outside environment, in which recursion is probably the simplest way to go. But my problem is addressed by a different stackoverflow question, of which mine is a duplicate, so I guess I'm good! – Bill Evans at Mariposa Apr 02 '23 at 18:54
  • 1
    You might use a depth parameter in your method call and you can increase the paramater by one for any recursive call. So you always now how deep is your recursion at the moment. – B.R. Apr 02 '23 at 19:12
  • @B.R.: An earlier version of this program did indeed use a depth parameter. But it seems likely that the program will evolve so that it's not just one function calling itself recursively. Besides, that other stackoverflow question's answers provide juicy details to explore. – Bill Evans at Mariposa Apr 02 '23 at 20:49

0 Answers0