Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is my recursion limit not being respected?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 print or len calls inside your deepest recursive call;
  • plus whatever calls you made before your first recursive call, for instance to a main function;
  • plus possibly a small number of "invisible" calls made by the interpreter on top of the calls you made explicitly in your code.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading