Relate Frames to Function Calls
Core idea
A frame represents an active or retained execution context. Its f_code identifies the code object, f_locals exposes local bindings, and f_back links to a caller frame when present. A function can be called multiple times with the same code but different frames. CPython 3.13 changed optimized-scope f_locals to a write-through proxy; this lesson only reads it.
import sysdef measure(n): total = n * 2 frame = sys._getframe() try: print(frame.f_code.co_name, frame.f_locals['total']) finally: del framemeasure(4)The active frame refers to measure’s code and current local total. Deleting the extra reference avoids retaining it unnecessarily.
Expected output:
measure 8Inspect the caller
import sysdef inner(): frame = sys._getframe() try: print(frame.f_back.f_code.co_name) print(frame.f_back.f_locals['tag']) finally: del framedef outer(): tag = 'batch' inner()outer()The caller frame supplies outer’s code and binding. This is an introspection demonstration, not an argument-passing design.
Expected output:
outerbatchCommon mistake
Avoid retaining frame references or logging arbitrary f_locals; they can retain objects and expose secrets. sys._getframe is implementation-specific and not guaranteed on other Python interpreters.
Practice
Inspect the same function with two arguments and compare the local values and code name; never retain the frames beyond the demonstration.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Frames and calls
Check your understanding of frames and calls.
What is printed?
import sysdef f(): return sys._getframe().f_code.co_nameprint(f())What is printed?
def f(n): return locals()['n']print(f(5))Which frame field identifies the executed code?
Why avoid retaining frames?