DEV Community

Muhammad Atif Iqbal
Muhammad Atif Iqbal

Posted on

`inspect.stack()` in Python with Examples

๐Ÿ” Understanding inspect.stack() in Python with Examples

When you use Pythonโ€™s inspect.stack(), it gives you a list of frames representing the current call stack.
Each element is a 6-tuple:

  1. frame (frame_record[0]) โ†’ The execution environment (locals, globals).
  2. filename (frame_record[1]) โ†’ The file name where the code lives.
  3. lineno (frame_record[2]) โ†’ The line number being executed.
  4. function (frame_record[3]) โ†’ The function name being executed.
  5. code_context (frame_record[4]) โ†’ A snippet of source code being run.
  6. index (frame_record[5]) โ†’ Which line of the code context is active.

Letโ€™s break these with 5 different examples each.


1. Frame (frame_record[0])

This is the actual frame object: an environment where Python is executing.
You can use it to see local variables.

Examples

import inspect

def foo(x):
    stack = inspect.stack()
    frame = stack[0][0]   # current frame
    print(frame.f_locals) # show local variables

foo(10)
Enter fullscreen mode Exit fullscreen mode

๐Ÿ‘‰ Output: {'x': 10, 'stack': [...], 'frame': <frame object ...>}

Other uses:

  1. See which variables are in scope.
  2. Modify local variables dynamically (advanced).
  3. Access global variables.
  4. Debugging when you donโ€™t know whatโ€™s available.
  5. Introspection tools (like Django debug toolbar).

2. Filename (frame_record[1])

This gives you the file name where the function is running.

Examples

import inspect

def bar():
    stack = inspect.stack()
    print(stack[0][1])  # filename

bar()
Enter fullscreen mode Exit fullscreen mode

๐Ÿ‘‰ Output: /home/user/my_script.py

Other uses:

  1. Logging errors with file location.
  2. Auto-documentation (e.g., Sphinx-like tools).
  3. Debugging when you forget which file a function lives in.
  4. Security: detect if code is executed from a wrong file.
  5. Cross-file function tracing.

3. Line Number (frame_record[2])

This tells you the line number inside the file.

Examples

import inspect

def baz():
    stack = inspect.stack()
    print(stack[0][2])  # line number

baz()
Enter fullscreen mode Exit fullscreen mode

๐Ÿ‘‰ Output: 7 (or whatever line print is on)

Other uses:

  1. Show where an error happened.
  2. Trace execution step-by-step.
  3. Build a debugger.
  4. Logging warnings with file + line.
  5. Unit test coverage tools.

4. Function (frame_record[3])

This gives you the function name currently executing.

Examples

import inspect

def alpha():
    stack = inspect.stack()
    print(stack[0][3])  # function name

alpha()
Enter fullscreen mode Exit fullscreen mode

๐Ÿ‘‰ Output: alpha

Other uses:

  1. Dynamic logging (Entering function alpha).
  2. Profiling which function runs slow.
  3. Security: check only certain functions run.
  4. Frameworks (like Django middleware) detect caller.
  5. Debugging complex recursive functions.

5. Code Context (frame_record[4])

This is a list of lines of code currently running.
Itโ€™s usually 1 line.

Examples

import inspect

def beta():
    stack = inspect.stack()
    print(stack[0][4])  # code context

beta()
Enter fullscreen mode Exit fullscreen mode

๐Ÿ‘‰ Output: ['print(stack[0][4]) # code context\n']

Other uses:

  1. Show exact line being run (like traceback).
  2. Pretty error printing.
  3. Static analyzers (linting tools).
  4. Debugger that shows current code.
  5. Learning tools that display executed code.

6. Index (frame_record[5])

This is the index of the line in the code_context list.
Usually itโ€™s 0, but if multiple lines exist, it shows which one is running.

Examples

import inspect

def gamma():
    stack = inspect.stack()
    print(stack[0][5])  # index

gamma()
Enter fullscreen mode Exit fullscreen mode

๐Ÿ‘‰ Output: 0

Other uses:

  1. Multi-line expressions debugging.
  2. Syntax highlighting for running line.
  3. Editors showing current cursor position.
  4. Teaching tools for step-by-step code.
  5. Debuggers aligning executed line.

โœ… Summary

  • frame โ†’ Execution environment (variables).
  • filename โ†’ Which file is running.
  • lineno โ†’ Which line number.
  • function โ†’ Which function name.
  • code_context โ†’ The actual code text.
  • index โ†’ Position inside that code.

Top comments (0)