Back
+20 XP
Concept

Frame Inspection & Stack Introspection: sys._getframe

Every function execution creates an in-memory frame (`types.FrameType`) tracking the active bytecode index (`f_lasti`), local dictionary (`f_locals`), and the caller pointer (`f_back`). Inspecting frames via `sys._getframe()` enables deep debugging, dependency injection, and call-stack introspection 🕵️‍♂️📜.

python
import sys

def caller_service():
    request_id = "REQ_TX_98765"
    return logging_middleware()

def logging_middleware():
    # Inspect 1 level up the call stack:
    caller_frame = sys._getframe(1)
    caller_func = caller_frame.f_code.co_name
    caller_locals = caller_frame.f_locals

    print(f"Called by: '{caller_func}' with request_id={caller_locals.get('request_id')} 🚀")

caller_service()

# 86. Frame Inspection & Stack Introspection: sys._getframe Frameworks like Pytest, Sentry, and Loguru seem to magically know the exact line number, function name, and local variable values when an error occurs or a test fails. They do this by reading CPython's execution frame stack 🛑. ```python # The Call Stack Frame Linked List: # Current Frame -> f_back -> Caller Frame -> f_back -> Module Frame -> None # Frame attributes: # frame.f_code -> CodeType of the function # frame.f_locals -> Local variable dictionary # frame.f_lineno -> Current source line number # frame.f_lasti -> Bytecode instruction offset ``` ### Stack Frame Invariants 1. **Zero-Overhead Call Stack**: In CPython, execution frames are standard heap objects chained via `f_back`. Calling `sys._getframe(depth)` walks $N$ steps backward up this pointer chain in $O(N)$ time. 2. **`f_locals` Mutation Caveat**: While reading `frame.f_locals` is fast, mutating `frame.f_locals` directly inside optimized functions (`LOAD_FAST` reads C array slots, not the dictionary) does not reliably update local variables in modern CPython without calling `PyFrame_LocalsToFast()`. 3. **Internal Tools Only**: The leading underscore in `sys._getframe` warns that it is a CPython runtime internal, but it remains the foundational backbone of APM profilers, debuggers, and dependency injectors 🕵️‍♂️📜. --- ### Interactive Pop-Quiz 🧠 #### What does calling sys._getframe(1) return inside an executing Python function? - [ ] The execution frame object of the immediate calling function (one level up the call stack) 🕵️‍♂️ - [ ] The root execution frame of the operating system Linux kernel - [ ] A newly created empty thread object - [ ] The standard output buffer of the current terminal --- ### Practical Challenge 🎯 Implement a function `get_caller_info()` that uses `sys._getframe(1)` to return a tuple `(caller_name, caller_line)`. Create a function `run_experiment()` that calls `get_caller_info()`. Assert that `caller_name == 'run_experiment'` and `isinstance(caller_line, int)`. Print the caller function name. <details> <summary>Solution</summary> ```python import sys def get_caller_info(): frame = sys._getframe(1) return frame.f_code.co_name, frame.f_lineno def run_experiment(): return get_caller_info() name, line = run_experiment() assert name == "run_experiment" assert isinstance(line, int) print(name) ``` </details>

Checkpoint

What does calling `sys._getframe(1)` return inside an executing Python function? 🧠

Practice

Implement a function `get_caller_info()` that uses `sys._getframe(1)` to return a tuple `(caller_name, caller_line)`. Create a function `run_experiment()` that calls `get_caller_info()`. Assert that `caller_name == 'run_experiment'` and `isinstance(caller_line, int)`. Print the caller function name. 🎯

Terminal
01
Tap code blocks below to assemble
Available Blocks