Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Python sys.getrecursionlimit() method



The Python sys.getrecursionlimit() method is used to retrieve the current maximum depth of the Python interpreter's call stack which is the limit set for the maximum number of nested function calls that the interpreter can handle before raising a RecursionError.

This limit is in place to prevent infinite recursion from causing a stack overflow and crashing the program. By using sys.getrecursionlimit() method developers can check the current recursion limit and if necessary and adjust it to handle deeper recursion levels for specific use cases.

Syntax

Following is the syntax and parameters of Python sys.getrecursionlimit() method −

sys.getrecursionlimit()

Parameter

This method does not take any parameters.

Return value

This method returns the current recursion limit of the Python interpreter.

Example 1

Following is the example of simply retrieving and printing the current recursion limit which is typically 1000 by default −

import sys

# Get the current recursion limit
current_limit = sys.getrecursionlimit()
print(f"Current recursion limit: {current_limit}")   

Output

Current recursion limit: 1000

Example 2

This example shows how to get the default recursion limit, change it using the sys.setrecursionlimit() method and then retrieve the new limit to confirm the change −

import sys

# Get the default recursion limit
default_limit = sys.getrecursionlimit()
print(f"Default recursion limit: {default_limit}")

# Set a new recursion limit
sys.setrecursionlimit(2000)

# Get the new recursion limit
new_limit = sys.getrecursionlimit()
print(f"New recursion limit: {new_limit}")

Output

Default recursion limit: 1000
New recursion limit: 2000

Example 3

This example shows checking the current recursion limit before performing a deep recursion and then increasing the limit to accommodate deeper recursion −

import sys

# Function with deep recursion
def deep_recursion(n):
    if n == 0:
        return "Reached the end"
    else:
        return deep_recursion(n - 1)

# Check the current recursion limit
limit = sys.getrecursionlimit()
print(f"Current recursion limit: {limit}")

# Attempt a deep recursion
try:
    result = deep_recursion(limit - 5)  # Just below the limit
    print(result)
except RecursionError:
    print("Recursion limit exceeded")

# Increase the recursion limit and try again
sys.setrecursionlimit(limit + 1000)
new_limit = sys.getrecursionlimit()
print(f"New recursion limit: {new_limit}")

try:
    result = deep_recursion(new_limit - 5)  # Just below the new limit
    print(result)
except RecursionError:
    print("Recursion limit exceeded")

Output

Current recursion limit: 1000
Reached the end
New recursion limit: 2000
Reached the end
python_modules.htm
Advertisements