How do I get the current depth of the Python interpreter stack?

核能气质少年 提交于 2019-11-29 14:41:07

You can see the whole call stack from inspect.stack(), so currently taken depth would be len(inspect.stack()).

On the other hand, I guess you got the complete stack printed out when "maximum recursion depth exceeded" exception was raised. That stack trace should show you exactly what went wrong.

If speed is an issue, it's way faster to bypass inspect module.

def get_stack_size():
    """Get stack size for caller's 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's frame always exist
    while True:
        try:
            sys._getframe(size)
            size += 1
        except ValueError:
            return size - 1  # subtract current frame
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!