[파이썬] `sys.setrecursionlimit()`: 최대 재귀 깊이 설정

Recursion is a powerful technique used in programming, where a function calls itself repeatedly until a certain condition is met. However, excessive recursion can lead to a “RecursionError” due to the maximum recursion depth being exceeded. In Python, the default maximum recursion depth is 1000.

To overcome this limitation and adjust the maximum recursion depth according to our needs, we can make use of the sys.setrecursionlimit() function. This function allows us to set a new maximum recursion depth.

Adjusting the Maximum Recursion Depth

To change the maximum recursion depth, follow these steps:

  1. Import the sys module:
import sys
  1. Call the sys.setrecursionlimit() function and provide the desired new maximum recursion depth as an argument. For example, to set the new maximum recursion depth to 2000:
sys.setrecursionlimit(2000)

Example Usage

Let’s see an example of how to use sys.setrecursionlimit():

import sys

def recursive_function(n):
    if n <= 0:
        return
    else:
        print(n)
        recursive_function(n-1)

sys.setrecursionlimit(5000)  # Set new maximum recursion depth

recursive_function(10)

In this example, we have a simple recursive function, recursive_function(), that prints the value of n and recursively calls itself with n-1 as the argument, until n reaches 0. We set the new maximum recursion depth to 5000 before calling the recursive_function().

Important Considerations

By using sys.setrecursionlimit(), we have the flexibility to adjust the maximum recursion depth for our Python programs. However, we should always exercise caution and consider the potential consequences of increasing this limit.