How to retrieve 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 gets added to the stack. In order to avoid infinite recursion from occurring that can lead to the overflowing of the stack, every programming language has a recursion limit. This limit varies depending on the programming language and the platform.
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 getrecursionlimit() method of the sys module
The getrecursionlimit() method of the sys module returns the current value of the recursion limit. We can use setrecursionlimit() to modify it. Learn more about setrecusrsionlimit() here.
Syntax
getrecursionlimit()
Parameters
This method has no parameters.
Return value
This method returns the maximum recursion limit.
Code
import sysplatform = sys.platformrecur_limit = sys.getrecursionlimit()print("The recursion limit for %s platform is %s" % (platform, recur_limit))
Explanation
- Line 1: The
sysmodule is imported. - Line 3: We obtained the current operating system using the sys.platform constant.
- Line 4: The maximum recursion depth is obtained using the
sys.getrecursionlimit()method. - Line 5: The current operating system and recursion limit are printed.