Trace Evaluation Stack Effects
Core idea
CPython evaluates many operations with a stack of intermediate values. dis.stack_effect(opcode, oparg) reports the net stack-depth change for a particular instruction. For a branch, jump=True or False selects the path when supported. A positive net effect pushes more than it pops; a negative effect pops more than it pushes. This is not a complete simulation of values or exception paths.
import disdef add(a, b): return a + bdepth = 0for i in dis.get_instructions(add): delta = dis.stack_effect(i.opcode, i.arg) depth += delta print(i.opname, delta, depth)The fused load pushes two operands in this version; addition replaces two values with one; return removes that result.
Expected output:
RESUME 0 0LOAD_FAST_LOAD_FAST 2 2BINARY_OP -1 1RETURN_VALUE -1 0Inspect a branch edge
import discode = compile('for x in (1, 2):\n pass\n', '<loop>', 'exec')i = next(i for i in dis.get_instructions(code) if i.opname == 'FOR_ITER')print(dis.stack_effect(i.opcode, i.arg, jump=False))print(dis.stack_effect(i.opcode, i.arg, jump=True))On CPython 3.13.5 FOR_ITER has net +1 on both reported edges; END_FOR and POP_TOP participate in loop-exit cleanup. Analyze the actual target instructions, not an older version’s iterator-pop rule.
Expected output:
11Common mistake
Do not add stack effects linearly across jumps or handlers. Analyze feasible control-flow paths and their entry depths; stack_effect describes net effects, not operand identity.
Practice
Trace a straight-line multiplication function, then a conditional function. Separate branch paths and compare their stack-depth changes.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Stack effects
Check your understanding of stack effects.
What is printed?
import disprint(dis.stack_effect(dis.opmap['POP_TOP']))What is printed?
import disprint(dis.stack_effect(dis.opmap['LOAD_CONST'],0))What does net stack effect measure?
Why analyze control-flow paths separately?