How to Measure Python Stack Depth with inspect.stack()

Measure the current call stack depth in Python using the inspect module to understand recursion depth and debug execution context.

Easy Python 3.9+ Aug 9, 2026 Errors & debugging 16 views 0 copies

Python code

15 lines
Python 3.9+
import inspect

def stack_depth():
    return len(inspect.stack())

def recursive_function(n):
    if n == 0:
        print(f"Base case reached. Stack depth: {stack_depth()}")
        return
    recursive_function(n - 1)

if __name__ == "__main__":
    print(f"Initial stack depth: {stack_depth()}")
    recursive_function(3)
    print(f"Stack depth after recursion: {stack_depth()}")

Output

stdout
Initial stack depth: 3
Base case reached. Stack depth: 7
Stack depth after recursion: 3

How it works

The inspect.stack() function returns the current call stack as a list of frame records, where the length corresponds to the depth of execution. Each recursive call adds one frame to the stack, so stack_depth() grows by one each level. The initial depth of 3 reflects the __main__ module, the function call, and the inspect internal frame. After recursion completes, the stack unwinds back to the original depth, demonstrating that the stack is transient.

Common mistakes

  • Forgetting that `inspect.stack()` includes internal frames like `__main__` and `inspect`, making the depth appear larger than expected
  • Calling `stack_depth()` inside a list comprehension or generator which adds extra hidden frames
  • Using `inspect.stack()` in a hot loop where it hurts performance due to frame creation overhead

Variations

  1. Use `sys._getframe()` to get a single frame instead of the full stack for lighter-weight introspection
  2. Track recursion depth manually by passing a counter parameter for predictable measurement without introspection

Real-world use cases

  • Debugging deeply recursive algorithms to see how close you are to Python's default recursion limit of 1000 frames.
  • Building logging utilities that include the caller's context by inspecting the stack trace for better diagnostics.
  • Implementing a code profiler that measures stack depth to identify potential stack overflow risks in production services.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Errors & debugging

Related tutorials and quizzes for this topic.