Skip to main content

Opcodes

A code object's co_code is a sequence of 2-byte instructions. Each instruction is (opcode, oparg). Larger opargs are produced by prepending one to three EXTENDED_ARG instructions.

Source-of-record: Python/bytecodes.c, Include/opcode_ids.h, Python/specialize.c, CPython bytecode documentation.

Encoding

FieldBitsMeaning
Opcode8Operation.
Oparg8Operand.
EXTENDED_ARG16Shift oparg left by 8 and prepend bits.

EXTENDED_ARG may be chained up to three times, producing a 32-bit oparg.

Inline caches

Most specialised opcodes carry inline cache words immediately after the instruction. The co_code reads (instruction, cache0, cache1, ...). Cache words are not executed; the dispatcher skips over them by adding _PyOpcode_Caches[op] to the program counter.

Opcode categories

Stack manipulation

OpcodeStack effectDescription
NOP0No operation.
POP_TOP-1Remove TOS.
PUSH_NULL+1Push NULL marker.
COPY <i>+1Push TOS[-i].
SWAP <i>0Swap TOS and TOS[-i+1].
END_FOR-1Discard for-loop iterator state.
END_SEND-1Discard send-target.

Unary operators

OpcodeStack effectEffect
UNARY_NEGATIVE0TOS = -TOS
UNARY_NOT0TOS = not TOS
UNARY_INVERT0TOS = ~TOS
TO_BOOL0TOS = bool(TOS)
GET_LEN+1Push len(TOS).

Binary operators

OpcodeStack effectEffect
BINARY_OP <kind>-1TOS = TOS1 op TOS (kind selects op).
BINARY_SUBSCR-1TOS = TOS1[TOS].
BINARY_SLICE-2TOS = TOS3[TOS1:TOS].
STORE_SUBSCR-3TOS2[TOS] = TOS3.
STORE_SLICE-4TOS3[TOS1:TOS] = TOS4.
DELETE_SUBSCR-2del TOS1[TOS].

BINARY_OP <kind> covers + - * / // % ** @ << >> & \| ^ and their in-place variants. The kind byte selects the operator.

Constants and names

OpcodeEffect
LOAD_CONST <i>Push co_consts[i].
LOAD_NAME <i>Push name from locals, globals, builtins.
STORE_NAME <i>Pop and store in locals.
DELETE_NAME <i>Delete from locals.
LOAD_GLOBAL <i>Push globals or builtins by name.
STORE_GLOBAL <i>Pop into globals.
DELETE_GLOBAL <i>Delete from globals.
LOAD_FAST <i>Push co_varnames[i] from frame locals.
LOAD_FAST_LOAD_FASTTwo LOAD_FAST in one instruction.
LOAD_FAST_AND_CLEARLOAD_FAST followed by clearing the slot.
LOAD_FAST_CHECKLOAD_FAST that raises UnboundLocalError if unbound.
LOAD_FAST_BORROWLOAD_FAST without incrementing refcount.
STORE_FAST <i>Store into local slot.
STORE_FAST_LOAD_FASTSTORE_FAST + LOAD_FAST.
STORE_FAST_STORE_FASTTwo STORE_FAST in one instruction.
DELETE_FAST <i>Clear local slot.
LOAD_CLOSURE <i>Push cell object.
LOAD_DEREF <i>Push value from cell.
STORE_DEREF <i>Store into cell.
DELETE_DEREF <i>Clear cell.
MAKE_CELL <i>Promote local to cell.
COPY_FREE_VARS <n>Copy n free variables into new frame.

Attribute and method access

OpcodeEffect
LOAD_ATTR <i>TOS = TOS.<name>.
STORE_ATTR <i>TOS1.<name> = TOS.
DELETE_ATTR <i>del TOS.<name>.
LOAD_SUPER_ATTR <i>super().attr load (3.12+).
LOAD_METHOD (folded into LOAD_ATTR with low bit)Push bound method or NULL+function.

Building containers

OpcodeStack effectEffect
BUILD_LIST <n>-n+1Pop n items into a list.
BUILD_TUPLE <n>-n+1Pop n items into a tuple.
BUILD_SET <n>-n+1Pop n items into a set.
BUILD_MAP <n>-2n+1Pop n (k,v) pairs into a dict.
BUILD_CONST_KEY_MAP <n>-nPop values; keys is a tuple constant on TOS.
BUILD_STRING <n>-n+1Concatenate n strings.
BUILD_SLICE <n>variesConstruct slice (n=2 or 3).
LIST_EXTEND <i>-1list.extend.
LIST_APPEND <i>-1list.append.
LIST_TO_TUPLE0Convert list to tuple.
SET_ADD <i>-1set.add.
SET_UPDATE <i>-1set.update.
MAP_ADD <i>-2dict.setitem.
DICT_UPDATE <i>-1dict.update.
DICT_MERGE <i>-1Merge with duplicate-key check.

Comparison and identity

OpcodeEffect
COMPARE_OP <op>TOS = TOS1 op TOS; op is one of <, <=, ==, !=, >, >=.
IS_OP <invert>TOS = (TOS1 is TOS) XOR invert.
CONTAINS_OP <invert>TOS = (TOS in TOS1) XOR invert.
CHECK_EXC_MATCHexception-match check used by except.
CHECK_EG_MATCHexception-group match used by except*.

Control flow

OpcodeEffect
JUMP_FORWARD <delta>Jump relative forward.
JUMP_BACKWARD <delta>Jump relative backward; ticks the eval breaker.
JUMP_BACKWARD_NO_INTERRUPTBackward jump without breaker check.
POP_JUMP_IF_TRUE <delta>Pop; jump if truthy.
POP_JUMP_IF_FALSE <delta>Pop; jump if falsy.
POP_JUMP_IF_NONE <delta>Pop; jump if is None.
POP_JUMP_IF_NOT_NONE <delta>Pop; jump if is not None.
FOR_ITER <delta>Call __next__; on StopIteration jump.
END_FORDrop the iterator after the loop.

Function call

OpcodeEffect
CALL <argc>Call TOS with argc positional args (NULL + fn frame).
CALL_KW <argc>Same with keyword args on top.
CALL_FUNCTION_EX <flags>Call with *args (and **kwargs if flag set).
KW_NAMES <i>Set keyword-name tuple for the next CALL.
MAKE_FUNCTION <flags>Build a function from a code object.
SET_FUNCTION_ATTRIBUTE <flag>Set __defaults__, __kwdefaults__, __annotations__, __closure__.
RETURN_VALUEPop and return.
RETURN_CONST <i>Return co_consts[i].
RETURN_GENERATORConvert frame into a generator object.
RESUME <where>Generator/coroutine resume point.
YIELD_VALUEYield TOS; suspend frame.
SEND <delta>Generator.send wrapper; jumps on exhausted.

Imports

OpcodeEffect
IMPORT_NAME <i>Call __import__ with name, fromlist, level.
IMPORT_FROM <i>Read submodule attribute.
IMPORT_STARBind every name from a module.

Exceptions

OpcodeEffect
PUSH_EXC_INFOSave and rotate the current exception.
POP_EXCEPTRestore prior exception state.
RERAISE <oparg>Re-raise stacked exception.
RAISE_VARARGS <n>Raise with 0, 1, or 2 args.
CLEANUP_THROWConvert StopIteration->RuntimeError per PEP 479.
LOAD_ASSERTION_ERRORPush the AssertionError class.
WITH_EXCEPT_STARTCall __exit__(type, val, tb).

With and context managers

OpcodeEffect
BEFORE_WITHSet up __enter__.
BEFORE_ASYNC_WITHSet up __aenter__.
WITH_EXCEPT_STARTOn exception, push args for __exit__.

Async support

OpcodeEffect
GET_AWAITABLE <flags>Convert to awaitable.
GET_AITER__aiter__.
GET_ANEXT__anext__.
END_ASYNC_FORCleanly end async for after StopAsyncIteration.

Class machinery

OpcodeEffect
LOAD_BUILD_CLASSPush builtins.__build_class__.
LOAD_LOCALSPush frame locals dict.
LOAD_FROM_DICT_OR_GLOBALS <i>Class-body name lookup.
LOAD_FROM_DICT_OR_DEREF <i>Class-body free-var lookup.

Pattern matching

OpcodeEffect
MATCH_MAPPINGPush bool: is TOS a mapping?
MATCH_SEQUENCEPush bool: is TOS a sequence (not str/bytes)?
MATCH_KEYSMatch keys for a mapping pattern.
MATCH_CLASS <count>Match class pattern.

Specialised forms

For every adaptive opcode (LOAD_ATTR, LOAD_GLOBAL, BINARY_OP, CALL, COMPARE_OP, STORE_ATTR, STORE_SUBSCR, UNPACK_SEQUENCE, SEND, FOR_ITER, TO_BOOL), PEP 659 emits specialised variants once the heuristics fire:

AdaptiveSpecialised forms
LOAD_ATTRLOAD_ATTR_INSTANCE_VALUE, LOAD_ATTR_MODULE, LOAD_ATTR_WITH_HINT, LOAD_ATTR_SLOT, LOAD_ATTR_CLASS, LOAD_ATTR_PROPERTY, LOAD_ATTR_GETATTRIBUTE_OVERRIDDEN, LOAD_ATTR_METHOD_*
LOAD_GLOBALLOAD_GLOBAL_MODULE, LOAD_GLOBAL_BUILTIN
BINARY_OPBINARY_OP_ADD_INT, BINARY_OP_SUBTRACT_INT, BINARY_OP_MULTIPLY_INT, ..._FLOAT, ..._UNICODE
CALLCALL_PY_EXACT_ARGS, CALL_PY_WITH_DEFAULTS, CALL_TYPE_1, CALL_STR_1, CALL_TUPLE_1, CALL_BOUND_METHOD_EXACT_ARGS, CALL_BUILTIN_*, CALL_LEN, CALL_ISINSTANCE, CALL_METHOD_DESCRIPTOR_*, CALL_CLASS_*, CALL_ALLOC_AND_ENTER_INIT, CALL_KW_BOUND_METHOD, CALL_KW_PY
COMPARE_OPCOMPARE_OP_INT, COMPARE_OP_FLOAT, COMPARE_OP_STR
STORE_ATTRSTORE_ATTR_INSTANCE_VALUE, STORE_ATTR_SLOT, STORE_ATTR_WITH_HINT
STORE_SUBSCRSTORE_SUBSCR_LIST_INT, STORE_SUBSCR_DICT
UNPACK_SEQUENCEUNPACK_SEQUENCE_TWO_TUPLE, UNPACK_SEQUENCE_TUPLE, UNPACK_SEQUENCE_LIST
SENDSEND_GEN
FOR_ITERFOR_ITER_LIST, FOR_ITER_TUPLE, FOR_ITER_RANGE, FOR_ITER_GEN
TO_BOOLTO_BOOL_BOOL, TO_BOOL_INT, TO_BOOL_LIST, TO_BOOL_NONE, TO_BOOL_STR, TO_BOOL_ALWAYS_TRUE

Each specialised form has a fixed cache layout. On miss it "deoptimises" back to the adaptive form by replacing itself in the instruction stream.

Intrinsics

CALL_INTRINSIC_1 <id> and CALL_INTRINSIC_2 <id> invoke compiler-defined helpers that do not warrant their own opcode:

IDPurpose
INTRINSIC_1_INVALIDReserved.
INTRINSIC_PRINTImplementation of REPL displayhook.
INTRINSIC_IMPORT_STARHelper for IMPORT_STAR.
INTRINSIC_STOPITERATION_ERRORPEP 479 conversion.
INTRINSIC_ASYNC_GEN_WRAPWrap async-gen yielded value.
INTRINSIC_UNARY_POSITIVE+x fallback.
INTRINSIC_LIST_TO_TUPLEConvert list -> tuple.
INTRINSIC_TYPEVARPEP 695 typevar creation.
INTRINSIC_PARAMSPECPEP 695 paramspec.
INTRINSIC_TYPEVARTUPLEPEP 695 typevartuple.
INTRINSIC_SUBSCRIPT_GENERICGeneric[...] evaluation.
INTRINSIC_TYPEALIAStype statement.

Exception table

The co_exceptiontable is a variable-length byte string describing ranges of bytecode and where to jump on exception. PEP 657 format:

entry := startoffset, endoffset, target, depth+lasti, mode

The runtime walks the table on raise; if no entry covers the current lasti, the frame unwinds.

Location table

co_linetable encodes per-instruction source location (start line, end line, start col, end col) using a variable-length compression. The decode algorithm lives in CPython internals -> Compile.

Gopy status

Opcode groupState
All Tier-1 opcodes listed aboveComplete.
All specialised variantsComplete.
IntrinsicsComplete.
Exception table formatComplete.
Location table formatComplete.
Tier-2 uopsPartial (about 14 of 285 ported).

Reference