co_code holds a code object’s instructions. The numbers below are those of
Python 3.14, taken from its own opcode module, and apply to every file whose
magic number is 3627. Only
instructions that a .pyc file can hold are listed: pseudo-instructions,
specialised forms and INSTRUMENTED_* forms are left out. The interpreter
writes the specialised and instrumented forms into its own copy of the code while it
runs, never into a file.
Encoding
co_code is a sequence of 16-bit code units, each one byte of opcode and
one byte of argument. Every instruction occupies one code unit, plus any
inline cache units after it. An instruction with no
argument still has the argument byte; it is zero, and it is ignored.
EXTENDED_ARG widens an argument. It goes before the instruction, and its argument becomes the higher byte: up to three prefixes give the following instruction a 32-bit argument.
Instructions numbered 44 and up use their argument, as do RESUME (128) and
ENTER_EXECUTOR (255). Those numbered below 44 do not.
opcode.hasarg lists the ones that do.
Inline caches
Some instructions are followed by a fixed number of 16-bit cache entries. The
interpreter fills them in while the program runs, to specialise the instruction. In a
file they are all zero. They are part of the instruction that precedes them:
dis hides them unless asked, as CACHE instructions. A reader
must step over them.
| Instruction | Code units | Contents |
|---|---|---|
BINARY_OP | 5 | counter, then 4 units for a descriptor |
CALL | 3 | counter, then 2 units for the function version |
CALL_KW | 3 | counter, then 2 units for the function version |
COMPARE_OP | 1 | counter |
CONTAINS_OP | 1 | counter |
FOR_ITER | 1 | counter |
JUMP_BACKWARD | 1 | counter |
LOAD_ATTR | 9 | counter, 2 units of type version, 2 of keys version, 4 for a descriptor |
LOAD_GLOBAL | 4 | counter, index, module keys version, builtins keys version |
LOAD_SUPER_ATTR | 1 | counter |
POP_JUMP_IF_FALSE | 1 | counter |
POP_JUMP_IF_NONE | 1 | counter |
POP_JUMP_IF_NOT_NONE | 1 | counter |
POP_JUMP_IF_TRUE | 1 | counter |
SEND | 1 | counter |
STORE_ATTR | 4 | counter, 2 units of type version, index |
STORE_SUBSCR | 1 | counter |
TO_BOOL | 3 | counter, then 2 units of version |
UNPACK_SEQUENCE | 1 | counter |
Every other instruction has no cache.
Jump arguments
A jump’s argument counts 16-bit code units, not bytes, and is relative to the point just after the instruction, past its inline caches. In bytes:
target = offset + 2 + 2 × caches ± 2 × argument
The sign is minus for JUMP_BACKWARD,
JUMP_BACKWARD_NO_INTERRUPT and END_ASYNC_FOR, and plus for
JUMP_FORWARD, FOR_ITER, SEND and the four
POP_JUMP_IF_* instructions.
When a loop ends, FOR_ITER’s target is an END_FOR, and the
interpreter carries on at the instruction after it. END_ASYNC_FOR does not
really jump: its argument is a pretend backward jump, used only so that branch
monitoring knows where the loop began.
Every instruction
The argument, where one is used, is called arg. Local slot numbers index
co_localsplusnames; a name index goes into co_names and a
constant index into co_consts.
| Name | Number | Meaning |
|---|---|---|
BINARY_OP | 44 | Pops two values, pushes the result. arg is the operator, which includes subscripting |
BINARY_SLICE | 1 | Pops end, start and container; pushes container[start:end] |
BUILD_INTERPOLATION | 45 | Pops a value, its source text and an optional format spec; pushes an Interpolation. arg bit 0 means a spec is present; arg >> 2 is the conversion (0 none, 1 !s, 2 !r, 3 !a) |
BUILD_LIST | 46 | Pops arg items, pushes a list |
BUILD_MAP | 47 | Pops 2 × arg items, keys and values in turn, and pushes a dictionary of arg entries |
BUILD_SET | 48 | Pops arg items, pushes a set |
BUILD_SLICE | 49 | arg is 2 or 3. Pops start and end, and step if 3; pushes a slice |
BUILD_STRING | 50 | Pops arg strings and pushes them joined |
BUILD_TEMPLATE | 2 | Pops a tuple of interpolations and a tuple of strings; pushes a Template, for a template string |
BUILD_TUPLE | 51 | Pops arg items, pushes a tuple |
CACHE | 0 | Not a real instruction. Opcode 0 is the value of a zeroed inline cache entry |
CALL | 52 | Pops arg arguments, then self or NULL, then the callable below them; calls it and pushes the result |
CALL_FUNCTION_EX | 4 | Pops a keyword mapping or NULL, an iterable of positional arguments, NULL and the callable; calls it and pushes the result. No argument |
CALL_INTRINSIC_1 | 53 | Replaces the top of the stack with the result of an intrinsic selected by arg |
CALL_INTRINSIC_2 | 54 | Pops two values and pushes the result of an intrinsic selected by arg |
CALL_KW | 55 | Like CALL, with a tuple of keyword names on top of the stack. arg counts positional and named arguments |
CHECK_EG_MATCH | 5 | For except*: splits the exception group below the top by the type on top; pushes the rest and the match |
CHECK_EXC_MATCH | 6 | Pops the type on top; pushes whether the exception below matches it |
CLEANUP_THROW | 7 | Handles an exception from throw() or close() during yield from or await. If the top is StopIteration, replaces the top three items with None and its value; otherwise re-raises it |
COMPARE_OP | 56 | Pops two values, pushes the comparison. See comparison operators for the argument |
CONTAINS_OP | 57 | Pops two values, pushes in, or not in if arg is 1 |
CONVERT_VALUE | 58 | Pops a value, pushes str (arg 1), repr (2) or ascii (3) of it |
COPY | 59 | Pushes a copy of the item arg places down, counting the top as 1 |
COPY_FREE_VARS | 60 | Copies arg free variables from the closure into the frame |
DELETE_ATTR | 61 | Pops an object; del obj.name. arg is a name index |
DELETE_DEREF | 62 | Empties the cell in slot arg |
DELETE_FAST | 63 | Deletes the local in slot arg |
DELETE_GLOBAL | 64 | Deletes a global. arg is a name index |
DELETE_NAME | 65 | Deletes a name. arg is a name index |
DELETE_SUBSCR | 8 | Pops key and container; del container[key] |
DICT_MERGE | 66 | Like DICT_UPDATE, but raises an error on a duplicate key |
DICT_UPDATE | 67 | Pops a mapping and adds it to the dictionary arg places down |
END_ASYNC_FOR | 68 | Ends an async for: pops the async iterator and the exception; re-raises it unless it is StopAsyncIteration. arg is a pretend backward jump, for monitoring |
END_FOR | 9 | Pops the top value. Marks the end of a for loop; FOR_ITER goes past it when the loop ends |
END_SEND | 10 | Removes the sub-iterator below the top, when a yield from or await finishes |
ENTER_EXECUTOR | 255 | Only exists at run time: hands over to code made by the optimiser. Not expected in a file |
EXIT_INIT_CHECK | 11 | Pops the value __init__ returned and raises TypeError unless it is None. Used by the interpreter internally |
EXTENDED_ARG | 69 | Gives the next instruction’s argument more high bits |
FORMAT_SIMPLE | 12 | Pops a value, pushes value.__format__("") |
FORMAT_WITH_SPEC | 13 | Pops a spec and a value, pushes value.__format__(spec) |
FOR_ITER | 70 | Calls __next__() on the iterator on top and pushes the value, leaving the iterator below it. When the iterator is exhausted, jumps forward by arg and past the END_FOR there |
GET_AITER | 14 | Replaces the top with __aiter__() of it |
GET_ANEXT | 15 | Pushes an awaitable of __anext__() of the top |
GET_AWAITABLE | 71 | Replaces the top with an awaitable. arg is 1 after __aenter__, 2 after __aexit__, else 0 |
GET_ITER | 16 | Replaces the top with iter() of it |
GET_LEN | 18 | Pushes len() of the top |
GET_YIELD_FROM_ITER | 19 | Leaves a generator or coroutine on top unchanged; replaces anything else with iter() of it. For yield from |
IMPORT_FROM | 72 | Pushes an attribute of the module on top. arg is a name index |
IMPORT_NAME | 73 | Pops level and fromlist; pushes the imported module. arg is a name index |
INTERPRETER_EXIT | 20 | Leaves the interpreter loop. Used only by the interpreter’s internal frames |
IS_OP | 74 | Pops two values, pushes is, or is not if arg is 1 |
JUMP_BACKWARD | 75 | Jumps back by arg and checks for interrupts |
JUMP_BACKWARD_NO_INTERRUPT | 76 | Jumps back by arg without checking for interrupts |
JUMP_FORWARD | 77 | Jumps forward by arg |
LIST_APPEND | 78 | Pops an item and appends it to the list arg places down |
LIST_EXTEND | 79 | Pops an iterable and extends the list arg places down |
LOAD_ATTR | 80 | Replaces the top with an attribute of it. The name index is arg >> 1; bit 0 asks for a method load, pushing the method and self, or the attribute and NULL, for CALL |
LOAD_BUILD_CLASS | 21 | Pushes the function builtins.__build_class__, which a following call uses to make a class |
LOAD_COMMON_CONSTANT | 81 | Pushes a built-in object selected by arg |
LOAD_CONST | 82 | Pushes a constant. arg is a constant index |
LOAD_DEREF | 83 | Pushes the object in the cell in slot arg |
LOAD_FAST | 84 | Pushes the local in slot arg, which is known to be set |
LOAD_FAST_AND_CLEAR | 85 | Pushes the local in slot arg, or NULL, and clears it |
LOAD_FAST_BORROW | 86 | Pushes a borrowed reference to the local in slot arg, used where the compiler knows the local outlives the value on the stack |
LOAD_FAST_BORROW_LOAD_FAST_BORROW | 87 | Pushes borrowed references to two locals: slots arg >> 4 and arg & 15 |
LOAD_FAST_CHECK | 88 | Pushes the local in slot arg, or raises UnboundLocalError |
LOAD_FAST_LOAD_FAST | 89 | Pushes two locals: slots arg >> 4 and arg & 15 |
LOAD_FROM_DICT_OR_DEREF | 90 | Pops a mapping and looks up the name of slot arg in it; falls back to the cell |
LOAD_FROM_DICT_OR_GLOBALS | 91 | Pops a mapping and looks up a name in it, then in globals and builtins. arg is a name index |
LOAD_GLOBAL | 92 | Pushes a global. The name index is arg >> 1; if bit 0 is set, a NULL is also pushed for a call |
LOAD_LOCALS | 22 | Pushes the locals dictionary |
LOAD_NAME | 93 | Pushes a name found in locals, globals or builtins. arg is a name index |
LOAD_SMALL_INT | 94 | Pushes the integer arg, from 0 to 255 |
LOAD_SPECIAL | 95 | Looks up a special method selected by arg on the type of the top item. Replaces the item with the method and the item, or with a bound method and NULL |
LOAD_SUPER_ATTR | 96 | Pops self, the class and super; loads an attribute. The name index is arg >> 2; bit 0 asks for a method load; bit 1 marks the two-argument super |
MAKE_CELL | 97 | Makes a new cell in slot arg, holding the slot’s value if it has one |
MAKE_FUNCTION | 23 | Pushes a function made from the code object on top. No argument: SET_FUNCTION_ATTRIBUTE adds defaults, closure and annotations |
MAP_ADD | 98 | Pops a value and key, stores them in the dictionary arg places down |
MATCH_CLASS | 99 | Pops the keyword names, class and subject; pushes a tuple of attributes, or None. arg is the number of positional sub-patterns |
MATCH_KEYS | 24 | The top is a tuple of keys, the item below a mapping. Pushes a tuple of the values, or None |
MATCH_MAPPING | 25 | Pushes whether the top is a mapping |
MATCH_SEQUENCE | 26 | Pushes whether the top is a sequence and not text or bytes |
NOP | 27 | Does nothing |
NOT_TAKEN | 28 | Does nothing. Marks the fall-through side of a branch for monitoring |
POP_EXCEPT | 29 | Pops a value and uses it to restore the exception state |
POP_ITER | 30 | Removes the iterator on top, at the end of a loop |
POP_JUMP_IF_FALSE | 100 | Pops the top, which must be an exact bool; if false, jumps forward by arg |
POP_JUMP_IF_NONE | 101 | Pops the top; if None, jumps forward by arg |
POP_JUMP_IF_NOT_NONE | 102 | Pops the top; if not None, jumps forward by arg |
POP_JUMP_IF_TRUE | 103 | Pops the top, which must be an exact bool; if true, jumps forward by arg |
POP_TOP | 31 | Pops and discards the top |
PUSH_EXC_INFO | 32 | Pops a value, pushes the current exception, pushes the value back |
PUSH_NULL | 33 | Pushes NULL, for the calling sequence |
RAISE_VARARGS | 104 | Raises: arg 0 re-raises, 1 raises the top, 2 raises the item below the top with the top as its cause |
RERAISE | 105 | Pops the exception on top and re-raises it. If arg is nonzero, first sets f_lasti from the offset found arg places below the exception |
RESERVED | 17 | A reserved number. Executing it is an interpreter error |
RESUME | 128 | No visible effect; a point for tracing, debugging and optimisation checks. arg says where it is |
RETURN_GENERATOR | 34 | Makes a generator, coroutine or async generator from the frame and returns it |
RETURN_VALUE | 35 | Returns the top of the stack |
SEND | 106 | Sends the value on top into the sub-iterator below it, for yield from and await, and replaces the top with the result. When the sub-iterator returns, jumps forward by arg |
SETUP_ANNOTATIONS | 36 | Makes __annotations__ an empty dictionary in the locals, if it is missing |
SET_ADD | 107 | Pops an item and adds it to the set arg places down |
SET_FUNCTION_ATTRIBUTE | 108 | Pops a function and a value, sets one attribute selected by arg, and pushes the function back |
SET_UPDATE | 109 | Pops an iterable and adds its items to the set arg places down |
STORE_ATTR | 110 | Pops an object and a value; sets the attribute. arg is a name index |
STORE_DEREF | 111 | Pops a value into the cell in slot arg |
STORE_FAST | 112 | Pops a value into the local in slot arg |
STORE_FAST_LOAD_FAST | 113 | Pops a value into slot arg >> 4, then pushes the local in slot arg & 15 |
STORE_FAST_STORE_FAST | 114 | Pops two values into slots arg >> 4 and arg & 15 |
STORE_GLOBAL | 115 | Pops a value into a global. arg is a name index |
STORE_NAME | 116 | Pops a value into a name. arg is a name index |
STORE_SLICE | 37 | Pops end, start, container and value; container[start:end] = value |
STORE_SUBSCR | 38 | Pops key, container and value; container[key] = value |
SWAP | 117 | Swaps the top with the item arg places down, counting the top as 1 |
TO_BOOL | 39 | Replaces the top with bool() of it |
UNARY_INVERT | 40 | Replaces the top with ~ of it |
UNARY_NEGATIVE | 41 | Replaces the top with - of it |
UNARY_NOT | 42 | Replaces the top, which must be an exact bool, with not of it |
UNPACK_EX | 118 | Unpacks the top with a starred target. The low byte of arg is the count before the list, and the high byte the count after it |
UNPACK_SEQUENCE | 119 | Replaces the top with its arg items, pushed right to left |
WITH_EXCEPT_START | 43 | For with: calls the __exit__ method that sits further down the stack with the exception on top, and pushes the result |
YIELD_VALUE | 120 | Pops the top and yields it. arg is 1 inside yield from or await, otherwise 0 |
Comparison operators
COMPARE_OP’s operator is arg >> 5, an index into this
list. Bit 4 (arg & 16) asks for the result to be converted to
bool. The low four bits are a mask of the outcomes that count as true
(1 unordered, 2 less, 4 greater, 8 equal), used by the interpreter’s specialised forms; for
a < b arg is 2, and for a >= b it is 172.
| Index | Operator |
|---|---|
| 0 | < |
| 1 | <= |
| 2 | == |
| 3 | != |
| 4 | > |
| 5 | >= |
BINARY_OP operators
| arg | Operator | arg | Operator |
|---|---|---|---|
| 0 | + | 13 | += |
| 1 | & | 14 | &= |
| 2 | // | 15 | //= |
| 3 | << | 16 | <<= |
| 4 | @ | 17 | @= |
| 5 | * | 18 | *= |
| 6 | % | 19 | %= |
| 7 | | | 20 | |= |
| 8 | ** | 21 | **= |
| 9 | >> | 22 | >>= |
| 10 | - | 23 | -= |
| 11 | / | 24 | /= |
| 12 | ^ | 25 | ^= |
| 26 | [], subscript: pops key and container, pushes container[key] |
Intrinsics
CALL_INTRINSIC_1:
| arg | Name | Does |
|---|---|---|
| 0 | INTRINSIC_1_INVALID | Not valid |
| 1 | INTRINSIC_PRINT | Prints the argument to standard output, in the REPL |
| 2 | INTRINSIC_IMPORT_STAR | import * from the module object given, into the local namespace |
| 3 | INTRINSIC_STOPITERATION_ERROR | Turns a StopIteration (or, in an async generator, StopAsyncIteration) that escapes a generator or coroutine into a RuntimeError |
| 4 | INTRINSIC_ASYNC_GEN_WRAP | Wraps an async generator value |
| 5 | INTRINSIC_UNARY_POSITIVE | Unary + |
| 6 | INTRINSIC_LIST_TO_TUPLE | Converts a list to a tuple |
| 7 | INTRINSIC_TYPEVAR | Creates a TypeVar |
| 8 | INTRINSIC_PARAMSPEC | Creates a ParamSpec |
| 9 | INTRINSIC_TYPEVARTUPLE | Creates a TypeVarTuple |
| 10 | INTRINSIC_SUBSCRIPT_GENERIC | typing.Generic subscripted with the argument |
| 11 | INTRINSIC_TYPEALIAS | Creates a TypeAliasType, for the type statement |
CALL_INTRINSIC_2:
| arg | Name | Does |
|---|---|---|
| 0 | INTRINSIC_2_INVALID | Not valid |
| 1 | INTRINSIC_PREP_RERAISE_STAR | Computes the exception group to raise from try–except* |
| 2 | INTRINSIC_TYPEVAR_WITH_BOUND | Creates a TypeVar with a bound |
| 3 | INTRINSIC_TYPEVAR_WITH_CONSTRAINTS | Creates a TypeVar with constraints |
| 4 | INTRINSIC_SET_FUNCTION_TYPE_PARAMS | Sets a function’s __type_params__ |
| 5 | INTRINSIC_SET_TYPEPARAM_DEFAULT | Sets a type parameter’s default |
Function attributes
The argument of SET_FUNCTION_ATTRIBUTE is one of these values. The value
to set is on the stack below the function.
| arg | Attribute |
|---|---|
| 0x01 | Tuple of defaults for positional parameters |
| 0x02 | Dictionary of keyword-only defaults |
| 0x04 | Tuple of strings holding parameter annotations |
| 0x08 | Tuple of cells for free variables, the closure |
| 0x10 | The annotate function, which computes annotations when they are asked for |
RESUME argument
| Bits | Meaning |
|---|---|
| 0–1 | 0 start of a function; 1 after yield; 2 after yield from; 3 after await |
| 2 | Set when the RESUME is at except-depth 1 |
LOAD_COMMON_CONSTANT
| arg | Object |
|---|---|
| 0 | AssertionError |
| 1 | NotImplementedError |
| 2 | tuple |
| 3 | all |
| 4 | any |
LOAD_SPECIAL
| arg | Method |
|---|---|
| 0 | __enter__ |
| 1 | __exit__ |
| 2 | __aenter__ |
| 3 | __aexit__ |