How Python Handles Recursion Limit: Explanation and Examples
Python sets a default
recursion limit to prevent infinite recursion from crashing the program. You can check or change this limit using the sys.getrecursionlimit() and sys.setrecursionlimit() functions.Syntax
Python provides two main functions in the sys module to handle recursion limits:
sys.getrecursionlimit(): Returns the current maximum depth of the Python interpreter stack.sys.setrecursionlimit(limit): Sets a new recursion limit to the integerlimit.
These control how many times a function can call itself before Python stops it to avoid crashing.
python
import sys # Get the current recursion limit current_limit = sys.getrecursionlimit() print(f"Current recursion limit: {current_limit}") # Set a new recursion limit sys.setrecursionlimit(2000) print(f"New recursion limit set to: {sys.getrecursionlimit()}")
Output
Current recursion limit: 3000
New recursion limit set to: 2000
Example
This example shows a simple recursive function that counts down from a number to zero. It demonstrates what happens when the recursion limit is reached.
python
import sys def countdown(n): if n == 0: return "Done" else: return countdown(n-1) try: print(countdown(10)) # Works fine print(countdown(3500)) # Likely to exceed default recursion limit except RecursionError as e: print(f"RecursionError caught: {e}")
Output
Done
RecursionError caught: maximum recursion depth exceeded in comparison
Common Pitfalls
Common mistakes when dealing with recursion limits include:
- Setting the recursion limit too high, which can crash the Python interpreter.
- Not handling
RecursionError, causing the program to stop unexpectedly. - Writing recursive functions without a proper base case, leading to infinite recursion.
Always ensure your recursive functions have a clear stopping condition and handle errors gracefully.
python
import sys def bad_recursion(n): # Missing base case causes infinite recursion return bad_recursion(n+1) try: bad_recursion(0) except RecursionError: print("Caught infinite recursion error") # Correct way with base case def good_recursion(n): if n > 10: return "Done" return good_recursion(n+1) print(good_recursion(0))
Output
Caught infinite recursion error
Done
Quick Reference
Summary tips for handling recursion limits in Python:
- Use
sys.getrecursionlimit()to check the current limit. - Use
sys.setrecursionlimit()to increase the limit carefully. - Always write a base case to stop recursion.
- Catch
RecursionErrorto handle deep recursion safely. - Be cautious raising the limit too high to avoid crashes.
Key Takeaways
Python limits recursion depth to prevent crashes using a recursion limit.
Use sys.getrecursionlimit() and sys.setrecursionlimit() to check and adjust the limit.
Always include a base case in recursive functions to stop recursion.
Handle RecursionError exceptions to avoid program crashes.
Avoid setting the recursion limit too high to keep your program stable.