Determining the maximum allowable setrecursionlimit value for Python

In the Python 2 documentation, the sys library contains the following (the bold part is my edit):

sys.setrecursionlimit(limit)

Set the maximum depth of the Python interpreter stack to limit. This limit prevents infinite recursion due to C and Python crashing.

The maximum possible limit depends on the platform. The user may need to set a limit higher if he has a program that requires deep recursion and a platform that supports a higher limit . This should be done with caution, because a too high limit can lead to failure.

What does it mean? Is this just a general "make sure you have enough memory to manage the extra stack space" or is there a specific size "for each stack" that can be used to calculate the required memory value? What happens to Python when it cannot get space?

+4
source share
1 answer

Why let's find out:

me@host$ docker run -m 4MB --cpuset-cpus=0 -it --rm python:3.5.1
Python 3.5.1 (default, Dec  9 2015, 00:12:22)
[GCC 4.9.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys, struct
>>> maxint = 2 ** (struct.Struct('i').size * 8 - 1) - 1
>>> sys.setrecursionlimit(maxint)
>>> def goodbye_world():
...  goodbye_world()
...
>>> goodbye_world()
me@host$

Welp. This seems to be a Python crash. Pretty fast when you give only 4 MB of RAM.

+1
source

Source: https://habr.com/ru/post/1625005/


All Articles