Lesson · Python Internals
Frames & Tracebacks
80 min readFrames & Tracebacks
Frames represent active execution contexts and tracebacks link frames that led to exceptions. These objects explain local namespaces, call stacks, debuggers, profilers, and some introspection costs.
Learning goals
- Explain what an execution frame holds for one call: the code object, the local namespace, and the current position.
- Reach the running frame with
inspect.currentframe()and move to its caller withf_back. - Distinguish local, global, and builtin namespace lookup and say where a frame fits.
- Read a printed traceback from its first frame to its last and name the function and line each entry points at.
- State why frame and traceback references deserve cleanup, and what cost
inspect.stack()adds.
Mental model
A frame exists for as long as a call is active, and frames chain toward their callers, which is what makes the call stack a stack. A traceback is the same chain captured when an exception travels outward: each entry records a frame and the line it was executing (the call line for the callers, the raise site at the end), so reading a printed report from the first frame to the last follows the calls that led to the failure.
Mental model
read it top to bottom
call outer() → a frame for outer (locals: value)
└─ call inner() → a frame for inner, linked to its caller
└─ raise → traceback entries record each frame and lineCore idea
Every active call owns a frame: the code object being executed, the local namespace, and the current position. Frames link to their caller, so the live collection of frames forms the call stack, and when an exception propagates, the traceback preserves that chain with line numbers. This is the machinery behind debuggers, inspect introspection, and the local-versus-global name lookup rules.
Execution frames
An execution frame combines a code object with runtime state for one active invocation. Frames link caller/callee context and are exposed through tracebacks and introspection.
Local/global namespaces
Local/global namespaces is a mapping between names and objects used during lookup. Python creates and consults different namespaces for modules, classes, functions, and built-ins.
Call stack
Each active function call has execution state on the call stack. Recursive algorithms therefore consume stack depth proportional to the longest active recursion path.
Traceback objects
A traceback object holds one entry per frame that an exception propagated through, linking each frame to the line that was executing and to the next entry in the chain. You reach it as the __traceback__ attribute of a caught exception, or from sys.exc_info(), and the traceback module formats it into the report you normally read. The chain preserves the whole call path, which is why an error report can name every function the exception passed through.
Frame inspection
Frame inspection reads the state of one active call: inspect.currentframe() returns the frame of the function that calls it, f_back follows the chain toward the caller, and f_code, f_locals, and f_lineno expose the code object, the local namespace, and the current position. It is a diagnostic tool rather than a hot-path technique, since reading f_locals builds a mapping for an optimized frame and inspect.stack() assembles a richer object for every frame in the chain.
Walkthrough
inspect.currentframe()returns the frame of the function that runs it, so insideinnerit is the frame forinner, not forouter; the frame'sf_backis the step toward the caller.frame.f_codeis that frame's code object, andco_namereports the function's name, which is why the first element printed is'inner'even though the call came fromouter.dict(frame.f_locals)copies the frame's local namespace at that moment;innertakes no parameters and defines no locals, so the dict comes back empty.- Predict before running: which function name prints (the caller or the current function), and what
f_localswould contain ifinnerbound a local before reading it.
Experiments to try
- Call
inner()from two different callers and check that the frame is alwaysinner; then walk one step outward withframe.f_backand print its code name. - Bind a local in
innerbefore readingf_localsand confirm the dict reflects it, including theframename itself once it is bound. - Trigger an exception inside a nested call, catch it, and print
traceback.format_exc(); label each frame entry with its function, line, and file. - After reading a frame, delete the reference with
del frameand explain why theinspectdocs recommend it (breaking reference cycles around frames, tracebacks, and locals).
Common mistakes
- Reading
inspect.currentframe()as the caller's frame: it returns the frame of the function that calls it, so the caller is onef_backstep away, not zero. - Holding frame or traceback references in long-lived containers: a frame reaches its locals and can cycle back to itself, so the kept object can retain a whole object graph.
- Calling
inspect.stack()or readingf_localsin a hot path: both build per-call objects, frame info and mapping copies, so they belong in diagnostics rather than inner loops. - Reading a printed traceback from the top and stopping at the first line: printing runs from the outermost frame and ends at the raise site, so the failing line is the last frame entry, just above the exception message.
Practice: Easy
- Run the worked example and annotate the output: which value came from the code object, and why the locals dict is empty.
- Call
inner()directly and throughouter(), and confirmco_nameis always'inner'; write one sentence saying which frame the function actually received. - Print
frame.f_back.f_code.co_nameinsideinner; state what relationship it reports.
Practice: Medium
- Write
describe_frame(frame)that printsco_name,f_lineno, and the sorted local names; call it from two nesting depths and compare the output. - Trigger a
ZeroDivisionErrorin a helper called through two wrapper layers, catch it, and printtraceback.format_exc(); count the frame entries and label caller versus callee for each. - Walk a traceback manually from a caught exception (
exc.__traceback__), printingtb_frame.f_code.co_nameandtb_linenoper entry; compare the manual order with the printed order.
Practice: Hard
- Build a call-chain report tool that walks
f_backfrom the current frame and prints the chain of code names until the module frame; run it at three nesting depths and use its output to describe the call stack model. - Measure
inspect.stack()inside a recursion of depth 100 against a direct call, and explain the overhead with what each stack entry builds. - Write a
catch_and_reporthelper that logs the last frame's name and line from a caught exception's traceback without swallowing the error; explain why logging traceback information beats loggingstr(exc)alone.
Lesson checklist
- I can describe a frame in one sentence: per-call state combining a code object, a namespace, and a position.
- I can read a frame's
co_nameandf_localsand say which call they belong to. - I can walk
f_backto build the call chain from a running function to the module. - I can read a traceback report and identify the raise site and the callers leading to it.
Remember
A frame is the runtime state of one active call: which code object is running, what its local namespace holds, and where execution is. Frames chain through their callers to form the call stack, and a traceback preserves that chain when an exception propagates, which is the data every debugger and error report works from. Inspecting frames is cheap in small doses, but frame references keep locals alive, so inspect deliberately and release what you no longer need.
Interview angles
What is the main purpose of **Execution frames**?+
An execution frame combines a code object with runtime state for one active invocation. Frames link caller/callee context and are exposed through tracebacks and introspection.
What should you pay attention to when using **Local/global namespaces**?+
Local/global namespaces is a mapping between names and objects used during lookup. Python creates and consults different namespaces for modules, classes, functions, and built-ins.
How does **Call stack** fit into this lesson?+
Each active function call has execution state on the call stack. Recursive algorithms therefore consume stack depth proportional to the longest active recursion path.
What does `inspect.currentframe()` return, and how do you reach the caller's frame?+
It returns the frame of the function that calls it, so inside inner it is inner's frame, never the caller's. The caller is one step away through the f_back attribute, which chains toward the module frame.