Home > Software engineering >  Why does my function return a recursion error at 997 recursions instead of 1000?
Why does my function return a recursion error at 997 recursions instead of 1000?

Time:11-19

I'm not sure if this is the right place to ask, but I was messing with recursive functions, and noticed that while attempting recursion 997 my script returned a recursion error. The script I wrote was the following,

def main(x):
    print(x)
    x  = 1
    return main(x)

main(0)

After looking about online I opened the interpreter(?) in the powershell and tried sys.getrecursionlimit() and it returned 1000, I tried adding the same thing to the above script and it also returned 1000. So why did the error pop up before 1000 recursions? Did I write the function incorrectly or is there something else going on? If it helps, this is the full error message I got,

...
990
991
992
993
994
995
996
Traceback (most recent call last):
  File "test.py", line 6, in <module>
    main(0)
  File "test.py", line 4, in main
    return main(x)
  File "test.py", line 4, in main
    return main(x)
  File "test.py", line 4, in main
    return main(x)
  [Previous line repeated 992 more times]
  File "test.py", line 2, in main
    print(x)
RecursionError: maximum recursion depth exceeded while calling a Python object

Thanks!

CodePudding user response:

The recursion limit isn’t just the limit of recursive calls, it’s the limit on any nested calls — or, more precisely, the maximum number of stack frames. Here’s what the documentation says:

Return the current value of the recursion limit, the maximum depth of the Python interpreter stack.

In your case, your initial main call also counts, and so does the call to print. That’s why the RecursionError is raised in print. This brings us up to 999. Add the stack frame of the context from which main is called initially and now you’re at 1000.

Here’s a program which counts stack frames more accurately; we start at 1 (for the current stack frame), and add 1 for each call:

def main(n_frames):
    print(n_frames   1) #   1 for `print` call
    main(n_frames   1)

n_frames = 1
main(n_frames   1)

Incidentally, when I run this program (or yours), my program stops even earlier. This might be because Python inserts some additional frames due to bookkeeping. The value of sys.getrecursionlimit() isn’t intended as an absolutely precise limit that your code can depend on, it’s approximate and purely informative.

  • Related