How to get current Python interpreter stack depth?

From the documentation :

sys.getrecursionlimit()

Returns the current value of the recursion limit, the maximum depth of the Python interpreter stack. This limit prevents infinite recursion due to C and Python crashing. Setrecursionlimit () may be set.

I am currently pushing the recursion limit when etching an object. The object that I am etching has several levels of nesting, so I am a little puzzled by what is happening.

I managed to get around the problem with the following hack:

try:
    return pickle.dumps(x)
except:
    try:
        recursionlimit = getrecursionlimit()
        setrecursionlimit(2*recursionlimit)
        dumped = pickle.dumps(x)
        setrecursionlimit(recursionlimit)
        return dumped
    except:
        raise

Testing the above snippet in different contexts sometimes leads to success in the first try, and sometimes leads to success in the second try. So far, I have not been able to make an exception raise.

, . , , try .

, , , ?

def get_stack_depth():
    # what goes here?
+5
2

inspect.stack(), len(inspect.stack()).

, , , " ". , .

+10

, .

def get_stack_size():
    """Get stack size for caller frame.

    %timeit len(inspect.stack())
    8.86 ms ± 42.5 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
    %timeit get_stack_size()
    4.17 µs ± 11.5 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
    """
    size = 2  # current frame and caller frame always exist
    while True:
        try:
            sys._getframe(size)
            size += 1
        except ValueError:
            return size - 1  # subtract current frame
+4

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


All Articles