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.
Python code
15 linesimport 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
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
- Use `sys._getframe()` to get a single frame instead of the full stack for lighter-weight introspection
- 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
More from Errors & debugging
- Catch RecursionError and Fail Gracefully in Python easy
- Catch ValueError and print friendly message in Python easy
- Collect Multiple Validation Errors in Python Before Raising medium
- Handle ValueError and ZeroDivisionError in Python with try except easy
- How to Add a Correlation ID to Logging Records in Python medium
- How to Assert Preconditions with Descriptive Messages in Python easy
Keep learning
Related tutorials and quizzes for this topic.