How to set the recursion limit in Python

What is the recursion limit?

Recursion is a process by which a function calls itself, directly or indirectly. Every time a function is invoked, a new frame is added to the stack.

To avoid infinite recursion leading to the overflowing of the stack, every programming language has a recursion limit. This limit varies is programming languages and is platform dependent.

The sys module

The sys module provides access to the system-specific parameters and functions that interact and are maintained by the Python interpreter.

The setrecursionlimit() method

The setrecursionlimit() method of the sys module sets the maximum recursion depth of the Python interpreter.

Note: Depending on the program and platform, we can set a higher recursion limit. However, very high limits can cause the interpreter to crash.

This method raises a RecursionError when the given limit is too low at the current recursion depth.

Syntax

setrecursionlimit(limit)

Parameters

  • limit: This is the new value of the recursion limit.

Code

import sys
platform = sys.platform
recur_limit = sys.getrecursionlimit()
print("The recursion limit for %s platform is %s" % (platform, recur_limit))
sys.setrecursionlimit(2000)
new_recur_limit = sys.getrecursionlimit()
print("The new recursion limit for %s platform is %s" % (platform, new_recur_limit))

Explanation

  • Line 1: We import the sys module.
  • Line 3: We obtain the current operating system using the sys.platform constant.
  • Line 4: We obtain the maximum recursion depth using the sys.getrecursionlimit() method.
  • Line 5: We print the current operating system and the recursion limit.
  • Line 7: We set the recursion limit to 2000.
  • Line 8: We obtain the new maximum recursion depth using the sys.getrecursionlimit() method.
  • Line 9: We print the current operating system and the new recursion limit.

Free Resources