Observe Adaptive Specialization
Core idea
CPython can specialize frequently executed operations for observed operand types. dis.get_instructions(..., adaptive=True) exposes the current adaptive instruction view, whereas the default view uses original instructions. Inline caches and specialization decisions are implementation details. Warm-up, tracing, runtime build and input shapes may affect what appears.
import disdef add(a, b): return a + bprint([i.opname for i in dis.get_instructions(add) if 'BINARY_OP' in i.opname])for _ in range(100): add(2, 3)print([i.opname for i in dis.get_instructions(add, adaptive=True) if 'BINARY_OP' in i.opname])print(add(2, 3))The local CPython 3.13.5 run specializes integer addition. This exact name is observed, not promised.
Expected output:
['BINARY_OP']['BINARY_OP_ADD_INT']5Observe changed operand behavior
import disdef add(a, b): return a + bfor _ in range(100): add(1, 2)print(add('a', 'b'))print(any('BINARY_OP' in i.opname for i in dis.get_instructions(add)))A different supported operand pair still follows Python addition semantics. The default disassembly retains the generic view.
Expected output:
abTrueCommon mistake
Do not depend on specialization after a fixed call count or infer a speedup from an opcode name. Measure performance separately; do not use adaptive bytecode as a portable program format.
Practice
Compare original and adaptive disassembly for repeated integer and string operations. Record your runtime and whether specialization occurred, without asserting a required result.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Adaptive specialization
Check your understanding of adaptive specialization.
What is printed?
def add(a,b): return a+bfor _ in range(100): add(1,2)print(add('x','y'))What is printed?
import disdef f(a,b): return a+bprint(any(i.opname=='BINARY_OP' for i in dis.get_instructions(f,adaptive=False)))What does adaptive=True inspect?
Is specialization after exactly 100 calls a language guarantee?