dis — Desensamblador para bytecode de Python

Código fuente: Lib/dis.py


El módulo dis admite el análisis de CPython bytecode al desarmarlo. El bytecode de CPython que este módulo toma como entrada se define en el archivo Include/opcode.h y lo utilizan el compilador y el intérprete.

Detalles de implementación de CPython: Bytecode es un detalle de implementación del intérprete CPython. No se garantiza que el bytecode no se agregará, eliminará ni cambiará entre las versiones de Python. El uso de este módulo no debe considerarse para trabajar en diferentes máquinas virtuales Python o versiones de Python.

Distinto en la versión 3.6: Use 2 bytes para cada instrucción. Anteriormente, el número de bytes variaba según la instrucción.

Distinto en la versión 3.10: El argumento de las instrucciones de salto, manejo de excepciones y bucle ahora es el desplazamiento de instrucción en lugar del desplazamiento de byte.

Distinto en la versión 3.11: Some instructions are accompanied by one or more inline cache entries, which take the form of CACHE instructions. These instructions are hidden by default, but can be shown by passing show_caches=True to any dis utility. Furthermore, the interpreter now adapts the bytecode to specialize it for different runtime conditions. The adaptive bytecode can be shown by passing adaptive=True.

Distinto en la versión 3.12: The argument of a jump is the offset of the target instruction relative to the instruction that appears immediately after the jump instruction’s CACHE entries.

As a consequence, the presence of the CACHE instructions is transparent for forward jumps but needs to be taken into account when reasoning about backward jumps.

Distinto en la versión 3.13: The output shows logical labels rather than instruction offsets for jump targets and exception handlers. The -O command line option and the show_offsets argument were added.

Example: Given the function myfunc():

def myfunc(alist):
    return len(alist)

the following command can be used to display the disassembly of myfunc():

>>> dis.dis(myfunc)
  2           RESUME                   0

  3           LOAD_GLOBAL              1 (len + NULL)
              LOAD_FAST                0 (alist)
              CALL                     1
              RETURN_VALUE

(El «2» es un número de línea).

Command-line interface

The dis module can be invoked as a script from the command line:

python -m dis [-h] [-C] [-O] [infile]

The following options are accepted:

-h, --help

Display usage and exit.

-C, --show-caches

Show inline caches.

-O, --show-offsets

Show offsets of instructions.

If infile is specified, its disassembled code will be written to stdout. Otherwise, disassembly is performed on compiled source code recieved from stdin.

Análisis de bytecode

Nuevo en la versión 3.4.

La API de análisis de bytecode permite que partes del código Python se envuelvan en un objeto Bytecode que proporciona un fácil acceso a los detalles del código compilado.

class dis.Bytecode(x, *, first_line=None, current_offset=None, show_caches=False, adaptive=False, show_offsets=False)

Analiza el bytecode correspondiente a una función, generador, generador asíncrono, corutina, método, cadena de código fuente o un objeto de código (como lo retorna compile()).

Este es un contenedor conveniente para muchas de las funciones enumeradas a continuación, en particular get_instructions(), ya que iterar sobre una instancia de Bytecode produce las operaciones de bytecode como instancias de Instruction.

Si first_line no es None, indica el número de línea que se debe informar para la primera línea de origen en el código desmontado. De lo contrario, la información de la línea de origen (si la hay) se toma directamente del objeto de código desmontado.

Si current_offset no es None, se refiere a un desplazamiento de instrucción en el código desmontado. Establecer esto significa dis() mostrará un marcador de «instrucción actual» contra el código de operación especificado.

If show_caches is True, dis() will display inline cache entries used by the interpreter to specialize the bytecode.

If adaptive is True, dis() will display specialized bytecode that may be different from the original bytecode.

If show_offsets is True, dis() will include instruction offsets in the output.

classmethod from_traceback(tb, *, show_caches=False)

Construye una instancia de Bytecode a partir del traceback dado, estableciendo current_offset en la instrucción responsable de la excepción.

codeobj

El objeto de código compilado.

first_line

La primera línea de origen del objeto de código (si está disponible)

dis()

Retorna una vista formateada de las operaciones de bytecode (lo mismo que impreso por dis.dis(), pero retornado como una cadena de caracteres multilínea).

info()

Retorna una cadena de caracteres multilínea formateada con información detallada sobre el objeto de código, como code_info().

Distinto en la versión 3.7: Esto ahora puede manejar objetos generadores asíncronos y de corutinas.

Distinto en la versión 3.11: Added the show_caches and adaptive parameters.

Ejemplo:

>>> bytecode = dis.Bytecode(myfunc)
>>> for instr in bytecode:
...     print(instr.opname)
...
RESUME
LOAD_GLOBAL
LOAD_FAST
CALL
RETURN_VALUE

Funciones de análisis

El módulo dis también define las siguientes funciones de análisis que convierten la entrada directamente en la salida deseada. Pueden ser útiles si solo se realiza una sola operación, por lo que el objeto de análisis intermedio no es útil:

dis.code_info(x)

Retorna una cadena de caracteres multilínea formateada con información detallada del objeto de código para la función, generador, generador asíncrono, corutina, método, cadena de código fuente u objeto de código suministrados.

Tenga en cuenta que el contenido exacto de las cadenas de información de código depende en gran medida de la implementación y puede cambiar arbitrariamente en las diferentes máquinas virtuales Python o las versiones de Python.

Nuevo en la versión 3.2.

Distinto en la versión 3.7: Esto ahora puede manejar objetos generadores asíncronos y de corutinas.

dis.show_code(x, *, file=None)

Imprime información detallada del objeto de código para la función, método, cadena de código fuente u objeto de código suministrado en file (o sys.stdout si file no está especificado).

Esta es una abreviatura conveniente para print(code_info(x), file=file), destinado a la exploración interactiva en el indicador del intérprete (prompt).

Nuevo en la versión 3.2.

Distinto en la versión 3.4: Agrega un parámetro file.

dis.dis(x=None, *, file=None, depth=None, show_caches=False, adaptive=False)

Disassemble the x object. x can denote either a module, a class, a method, a function, a generator, an asynchronous generator, a coroutine, a code object, a string of source code or a byte sequence of raw bytecode. For a module, it disassembles all functions. For a class, it disassembles all methods (including class and static methods). For a code object or sequence of raw bytecode, it prints one line per bytecode instruction. It also recursively disassembles nested code objects. These can include generator expressions, nested functions, the bodies of nested classes, and the code objects used for annotation scopes. Strings are first compiled to code objects with the compile() built-in function before being disassembled. If no object is provided, this function disassembles the last traceback.

El desensamblaje se escribe como texto en el argumento file proporcionado si se proporciona y, de lo contrario, sys.stdout.

La profundidad máxima de recursión está limitada por depth a menos que sea None. depth=0 significa que no hay recursión.

If show_caches is True, this function will display inline cache entries used by the interpreter to specialize the bytecode.

If adaptive is True, this function will display specialized bytecode that may be different from the original bytecode.

Distinto en la versión 3.4: Agrega un parámetro file.

Distinto en la versión 3.7: Desensamblaje recursivo implementado y parámetro agregado depth.

Distinto en la versión 3.7: Esto ahora puede manejar objetos generadores asíncronos y de corutinas.

Distinto en la versión 3.11: Added the show_caches and adaptive parameters.

distb(tb=None, *, file=None, show_caches=False, adaptive=False,
show_offset=False)

Desmonta la función de inicio de pila de un rastreo, utilizando el último rastreo si no se pasó ninguno. Se indica la instrucción que causa la excepción.

El desensamblaje se escribe como texto en el argumento file proporcionado si se proporciona y, de lo contrario, sys.stdout.

Distinto en la versión 3.4: Agrega un parámetro file.

Distinto en la versión 3.11: Added the show_caches and adaptive parameters.

Distinto en la versión 3.13: Added the show_offsets parameter.

dis.disassemble(code, lasti=-1, *, file=None, show_caches=False, adaptive=False)
disco(code, lasti=-1, *, file=None, show_caches=False, adaptive=False,
show_offsets=False)

Desmonta un objeto de código, que indica la última instrucción si se proporcionó lasti. La salida se divide en las siguientes columnas:

  1. el número de línea, para la primera instrucción de cada línea

  2. la instrucción actual, indicada como -->,

  3. una instrucción etiquetada, indicada con >>,

  4. la dirección de la instrucción,

  5. el nombre del código de operación,

  6. parámetros de operación, y

  7. interpretación de los parámetros entre paréntesis.

La interpretación de parámetros reconoce nombres de variables locales y globales, valores constantes, objetivos de ramificación y operadores de comparación.

El desensamblaje se escribe como texto en el argumento file proporcionado si se proporciona y, de lo contrario, sys.stdout.

Distinto en la versión 3.4: Agrega un parámetro file.

Distinto en la versión 3.11: Added the show_caches and adaptive parameters.

Distinto en la versión 3.13: Added the show_offsets parameter.

dis.get_instructions(x, *, first_line=None, show_caches=False, adaptive=False)

Retorna un iterador sobre las instrucciones en la función, método, cadena de código fuente u objeto de código suministrado.

El iterador genera una serie de tuplas con nombre Instruction que dan los detalles de cada operación en el código suministrado.

Si first_line no es None, indica el número de línea que se debe informar para la primera línea de origen en el código desmontado. De lo contrario, la información de la línea de origen (si la hay) se toma directamente del objeto de código desmontado.

The adaptive parameter works as it does in dis().

Nuevo en la versión 3.4.

Distinto en la versión 3.11: Added the show_caches and adaptive parameters.

Distinto en la versión 3.13: The show_caches parameter is deprecated and has no effect. The cache_info field of each instruction is populated regardless of its value.

dis.findlinestarts(code)

This generator function uses the co_lines() method of the code object code to find the offsets which are starts of lines in the source code. They are generated as (offset, lineno) pairs.

Distinto en la versión 3.6: Los números de línea pueden estar disminuyendo. Antes, siempre estaban aumentando.

Distinto en la versión 3.10: The PEP 626 co_lines() method is used instead of the co_firstlineno and co_lnotab attributes of the code object.

Distinto en la versión 3.13: Line numbers can be None for bytecode that does not map to source lines.

dis.findlabels(code)

Detecta todos los desplazamientos en la cadena de caracteres de código de byte compilada code que son objetivos de salto y retorna una lista de estos desplazamientos.

dis.stack_effect(opcode, oparg=None, *, jump=None)

Calcula el efecto de pila de opcode con el argumento oparg.

Si el código tiene un objetivo de salto y jump es True, stack_effect() retornará el efecto de pila del salto. Si jump es False, retornará el efecto de acumulación de no saltar. Y si jump es None (predeterminado), retornará el efecto de acumulación máxima de ambos casos.

Nuevo en la versión 3.4.

Distinto en la versión 3.8: Agrega un parámetro jump.

Distinto en la versión 3.13: If oparg is omitted (or None), the stack effect is now returned for oparg=0. Previously this was an error for opcodes that use their arg. It is also no longer an error to pass an integer oparg when the opcode does not use it; the oparg in this case is ignored.

Instrucciones bytecode de Python

La función get_instructions() y clase Bytecode proporcionan detalles de las instrucciones bytecode como instancias Instruction:

class dis.Instruction

Detalles para una operación de bytecode

opcode

código numérico para la operación, correspondiente a los valores del opcode listados a continuación y los valores de bytecode en Colecciones opcode.

opname

nombre legible por humanos para la operación

baseopcode

numeric code for the base operation if operation is specialized; otherwise equal to opcode

baseopname

human readable name for the base operation if operation is specialized; otherwise equal to opname

arg

argumento numérico para la operación (si existe), de lo contrario None

oparg

alias for arg

argval

valor de argumento resuelto (si lo hay); de lo contrario, None

argrepr

descripción legible por humanos del argumento de la operación (si lo hay); de lo contrario, una cadena vacía.

offset

índice de inicio de operación dentro de la secuencia de bytecode

start_offset

start index of operation within bytecode sequence, including prefixed EXTENDED_ARG operations if present; otherwise equal to offset

cache_offset

start index of the cache entries following the operation

end_offset

end index of the cache entries following the operation

starts_line

True if this opcode starts a source line, otherwise False

line_number

source line number associated with this opcode (if any), otherwise None

is_jump_target

True si otro código salta aquí, de lo contrario, False

jump_target

bytecode index of the jump target if this is a jump operation, otherwise None

positions

Objeto dis.Positions que contiene las ubicaciones de inicio y finalización cubiertas por esta instrucción.

Nuevo en la versión 3.4.

Distinto en la versión 3.11: Se agrega el campo positions.

Distinto en la versión 3.13: Changed field starts_line.

Added fields start_offset, cache_offset, end_offset, baseopname, baseopcode, jump_target, oparg, line_number and cache_info.

class dis.Positions

En caso de que la información no esté disponible, algunos campos pueden ser None.

lineno
end_lineno
col_offset
end_col_offset

Nuevo en la versión 3.11.

El compilador de Python actualmente genera las siguientes instrucciones de bytecode.

Instrucciones generales

In the following, We will refer to the interpreter stack as STACK and describe operations on it as if it was a Python list. The top of the stack corresponds to STACK[-1] in this language.

NOP

Código que no hace nada. Utilizado como marcador de posición por el optimizador de bytecode y para generar eventos de seguimiento de línea.

POP_TOP

Removes the top-of-stack item:

STACK.pop()
END_FOR

Removes the top-of-stack item. Equivalent to POP_TOP. Used to clean up at the end of loops, hence the name.

Nuevo en la versión 3.12.

END_SEND

Implements del STACK[-2]. Used to clean up when a generator exits.

Nuevo en la versión 3.12.

COPY(i)

Push the i-th item to the top of the stack without removing it from its original location:

assert i > 0
STACK.append(STACK[-i])

Nuevo en la versión 3.11.

SWAP(i)

Swap the top of the stack with the i-th element:

STACK[-i], STACK[-1] = STACK[-1], STACK[-i]

Nuevo en la versión 3.11.

CACHE

En lugar de ser una instrucción real, este código de operación se usa para marcar espacio adicional para que el intérprete almacene en caché datos útiles directamente en el bytecode. Todas las utilidades dis lo ocultan automáticamente, pero se puede ver con show_caches=True.

Lógicamente, este espacio forma parte de la instrucción anterior. Muchos códigos de operación esperan ser seguidos por un número exacto de cachés y le indicarán al intérprete que los omita en tiempo de ejecución.

Los cachés poblados pueden parecer instrucciones arbitrarias, por lo que se debe tener mucho cuidado al leer o modificar el bytecode adaptativo sin procesar que contiene datos acelerados.

Nuevo en la versión 3.11.

Operaciones unarias

Las operaciones unarias toman la parte superior de la pila, aplican la operación y retornan el resultado a la pila.

UNARY_NEGATIVE

Implements STACK[-1] = -STACK[-1].

UNARY_NOT

Implements STACK[-1] = not STACK[-1].

Distinto en la versión 3.13: This instruction now requires an exact bool operand.

UNARY_INVERT

Implements STACK[-1] = ~STACK[-1].

GET_ITER

Implements STACK[-1] = iter(STACK[-1]).

GET_YIELD_FROM_ITER

If STACK[-1] is a generator iterator or coroutine object it is left as is. Otherwise, implements STACK[-1] = iter(STACK[-1]).

Nuevo en la versión 3.5.

TO_BOOL

Implements STACK[-1] = bool(STACK[-1]).

Nuevo en la versión 3.13.

Operaciones binarias e in situ

Binary operations remove the top two items from the stack (STACK[-1] and STACK[-2]). They perform the operation, then put the result back on the stack.

In-place operations are like binary operations, but the operation is done in-place when STACK[-2] supports it, and the resulting STACK[-1] may be (but does not have to be) the original STACK[-2].

BINARY_OP(op)

Implements the binary and in-place operators (depending on the value of op):

rhs = STACK.pop()
lhs = STACK.pop()
STACK.append(lhs op rhs)

Nuevo en la versión 3.11.

BINARY_SUBSCR

Implements:

key = STACK.pop()
container = STACK.pop()
STACK.append(container[key])
STORE_SUBSCR

Implements:

key = STACK.pop()
container = STACK.pop()
value = STACK.pop()
container[key] = value
DELETE_SUBSCR

Implements:

key = STACK.pop()
container = STACK.pop()
del container[key]
BINARY_SLICE

Implements:

end = STACK.pop()
start = STACK.pop()
container = STACK.pop()
STACK.append(container[start:end])

Nuevo en la versión 3.12.

STORE_SLICE

Implements:

end = STACK.pop()
start = STACK.pop()
container = STACK.pop()
values = STACK.pop()
container[start:end] = value

Nuevo en la versión 3.12.

Opcodes de corutinas

GET_AWAITABLE(where)

Implements STACK[-1] = get_awaitable(STACK[-1]), where get_awaitable(o) returns o if o is a coroutine object or a generator object with the CO_ITERABLE_COROUTINE flag, or resolves o.__await__.

Si el operando where es distinto de cero, indica dónde ocurre la instrucción:

  • 1: After a call to __aenter__

  • 2: After a call to __aexit__

Nuevo en la versión 3.5.

Distinto en la versión 3.11: Anteriormente, esta instrucción no tenía un oparg.

GET_AITER

Implements STACK[-1] = STACK[-1].__aiter__().

Nuevo en la versión 3.5.

Distinto en la versión 3.7: Ya no se admite el retorno de objetos awaitable de __aiter__.

GET_ANEXT

Implement STACK.append(get_awaitable(STACK[-1].__anext__())) to the stack. See GET_AWAITABLE for details about get_awaitable.

Nuevo en la versión 3.5.

END_ASYNC_FOR

Terminates an async for loop. Handles an exception raised when awaiting a next item. The stack contains the async iterable in STACK[-2] and the raised exception in STACK[-1]. Both are popped. If the exception is not StopAsyncIteration, it is re-raised.

Nuevo en la versión 3.8.

Distinto en la versión 3.11: La representación de excepciones en la pila ahora consta de uno, no de tres elementos.

CLEANUP_THROW

Handles an exception raised during a throw() or close() call through the current frame. If STACK[-1] is an instance of StopIteration, pop three values from the stack and push its value member. Otherwise, re-raise STACK[-1].

Nuevo en la versión 3.12.

BEFORE_ASYNC_WITH

Resolves __aenter__ and __aexit__ from STACK[-1]. Pushes __aexit__ and result of __aenter__() to the stack:

STACK.extend((__aexit__, __aenter__())

Nuevo en la versión 3.5.

Opcodes misceláneos

SET_ADD(i)

Implements:

item = STACK.pop()
set.add(STACK[-i], item)

Used to implement set comprehensions.

LIST_APPEND(i)

Implements:

item = STACK.pop()
list.append(STACK[-i], item)

Used to implement list comprehensions.

MAP_ADD(i)

Implements:

value = STACK.pop()
key = STACK.pop()
dict.__setitem__(STACK[-i], key, value)

Used to implement dict comprehensions.

Nuevo en la versión 3.1.

Distinto en la versión 3.8: Map value is STACK[-1] and map key is STACK[-2]. Before, those were reversed.

Para todas las instrucciones SET_ADD, LIST_APPEND y MAP_ADD, mientras el valor agregado o el par clave/valor aparece, el objeto contenedor permanece en la pila para que quede disponible para futuras iteraciones del bucle.

RETURN_VALUE

Returns with STACK[-1] to the caller of the function.

RETURN_CONST(consti)

Returns with co_consts[consti] to the caller of the function.

Nuevo en la versión 3.12.

YIELD_VALUE

Yields STACK.pop() from a generator.

Distinto en la versión 3.11: oparg set to be the stack depth.

Distinto en la versión 3.12: oparg set to be the exception block depth, for efficient closing of generators.

Distinto en la versión 3.13: oparg is 1 if this instruction is part of a yield-from or await, and 0 otherwise.

SETUP_ANNOTATIONS

Comprueba si __anotaciones__ está definido en locals(), si no está configurado como un dict vacío. Este código de operación solo se emite si el cuerpo de una clase o módulo contiene anotaciones de variables estáticamente.

Nuevo en la versión 3.6.

POP_EXCEPT

Extrae un valor de la pila, que se utiliza para restaurar el estado de excepción.

Distinto en la versión 3.11: La representación de excepciones en la pila ahora consta de uno, no de tres elementos.

RERAISE

Re-raises the exception currently on top of the stack. If oparg is non-zero, pops an additional value from the stack which is used to set f_lasti of the current frame.

Nuevo en la versión 3.9.

Distinto en la versión 3.11: La representación de excepciones en la pila ahora consta de uno, no de tres elementos.

PUSH_EXC_INFO

Extrae un valor de la pila. Agrega la excepción actual a la parte superior de la pila. Agrega el valor que apareció originalmente de vuelta a la pila. Se utiliza en los controladores de excepciones.

Nuevo en la versión 3.11.

CHECK_EXC_MATCH

Performs exception matching for except. Tests whether the STACK[-2] is an exception matching STACK[-1]. Pops STACK[-1] and pushes the boolean result of the test.

Nuevo en la versión 3.11.

CHECK_EG_MATCH

Performs exception matching for except*. Applies split(STACK[-1]) on the exception group representing STACK[-2].

En caso de coincidencia, extrae dos elementos de la pila y agrega el subgrupo que no coincide (None en caso de coincidencia total) seguido del subgrupo coincidente. Cuando no hay ninguna coincidencia, muestra un elemento (el tipo de coincidencia) y presiona None.

Nuevo en la versión 3.11.

WITH_EXCEPT_START

Llama a la función en la posición 4 de la pila con argumentos (tipo, val, tb) que representan la excepción en la parte superior de la pila. Se utiliza para implementar la llamada context_manager.__exit__(*exc_info()) cuando se ha producido una excepción en una sentencia with.

Nuevo en la versión 3.9.

Distinto en la versión 3.11: La función __exit__ está en la posición 4 de la pila en lugar de la 7. La representación de excepciones en la pila ahora consta de uno, no de tres, elementos.

LOAD_ASSERTION_ERROR

Inserta AssertionError en la pila. Utilizado por la declaración assert.

Nuevo en la versión 3.9.

LOAD_BUILD_CLASS

Pushes builtins.__build_class__() onto the stack. It is later called to construct a class.

BEFORE_WITH

Este código de operación realiza varias operaciones antes de que comience un bloque with. Primero, carga __exit__() desde el administrador de contexto y lo agrega a la pila para que WITH_EXCEPT_START lo use más tarde. Entonces, se llama __enter__(). Finalmente, el resultado de llamar al método __enter__() se agrega en la pila.

Nuevo en la versión 3.11.

GET_LEN

Perform STACK.append(len(STACK[-1])).

Nuevo en la versión 3.10.

MATCH_MAPPING

If STACK[-1] is an instance of collections.abc.Mapping (or, more technically: if it has the Py_TPFLAGS_MAPPING flag set in its tp_flags), push True onto the stack. Otherwise, push False.

Nuevo en la versión 3.10.

MATCH_SEQUENCE

If STACK[-1] is an instance of collections.abc.Sequence and is not an instance of str/bytes/bytearray (or, more technically: if it has the Py_TPFLAGS_SEQUENCE flag set in its tp_flags), push True onto the stack. Otherwise, push False.

Nuevo en la versión 3.10.

MATCH_KEYS

STACK[-1] is a tuple of mapping keys, and STACK[-2] is the match subject. If STACK[-2] contains all of the keys in STACK[-1], push a tuple containing the corresponding values. Otherwise, push None.

Nuevo en la versión 3.10.

Distinto en la versión 3.11: Anteriormente, esta instrucción también generaba un valor booleano que indicaba éxito (True) o falla (False).

STORE_NAME(namei)

Implements name = STACK.pop(). namei is the index of name in the attribute co_names of the code object. The compiler tries to use STORE_FAST or STORE_GLOBAL if possible.

DELETE_NAME(namei)

Implements del name, where namei is the index into co_names attribute of the code object.

UNPACK_SEQUENCE(count)

Unpacks STACK[-1] into count individual values, which are put onto the stack right-to-left. Require there to be exactly count values.:

assert(len(STACK[-1]) == count)
STACK.extend(STACK.pop()[:-count-1:-1])
UNPACK_EX(counts)

Implements assignment with a starred target: Unpacks an iterable in STACK[-1] into individual values, where the total number of values can be smaller than the number of items in the iterable: one of the new values will be a list of all leftover items.

The number of values before and after the list value is limited to 255.

The number of values before the list value is encoded in the argument of the opcode. The number of values after the list if any is encoded using an EXTENDED_ARG. As a consequence, the argument can be seen as a two bytes values where the low byte of counts is the number of values before the list value, the high byte of counts the number of values after it.

The extracted values are put onto the stack right-to-left, i.e. a, *b, c = d will be stored after execution as STACK.extend((a, b, c)).

STORE_ATTR(namei)

Implements:

obj = STACK.pop()
value = STACK.pop()
obj.name = value

where namei is the index of name in co_names of the code object.

DELETE_ATTR(namei)

Implements:

obj = STACK.pop()
del obj.name

where namei is the index of name into co_names of the code object.

STORE_GLOBAL(namei)

Funciona como STORE_NAME, pero almacena el nombre como global.

DELETE_GLOBAL(namei)

Funciona como DELETE_NAME, pero elimina un nombre global.

LOAD_CONST(consti)

Apila co_consts[consti] en la pila.

LOAD_NAME(namei)

Pushes the value associated with co_names[namei] onto the stack. The name is looked up within the locals, then the globals, then the builtins.

LOAD_LOCALS

Pushes a reference to the locals dictionary onto the stack. This is used to prepare namespace dictionaries for LOAD_FROM_DICT_OR_DEREF and LOAD_FROM_DICT_OR_GLOBALS.

Nuevo en la versión 3.12.

LOAD_FROM_DICT_OR_GLOBALS(i)

Pops a mapping off the stack and looks up the value for co_names[namei]. If the name is not found there, looks it up in the globals and then the builtins, similar to LOAD_GLOBAL. This is used for loading global variables in annotation scopes within class bodies.

Nuevo en la versión 3.12.

BUILD_TUPLE(count)

Creates a tuple consuming count items from the stack, and pushes the resulting tuple onto the stack.:

assert count > 0
STACK, values = STACK[:-count], STACK[-count:]
STACK.append(tuple(values))
BUILD_LIST(count)

Funciona como BUILD_TUPLE, pero crea una lista.

BUILD_SET(count)

Funciona como BUILD_TUPLE, pero crea un conjunto.

BUILD_MAP(count)

Pushes a new dictionary object onto the stack. Pops 2 * count items so that the dictionary holds count entries: {..., STACK[-4]: STACK[-3], STACK[-2]: STACK[-1]}.

Distinto en la versión 3.5: El diccionario se crea a partir de elementos de la pila en lugar de crear un diccionario vacío dimensionado previamente para contener count elementos.

BUILD_CONST_KEY_MAP(count)

The version of BUILD_MAP specialized for constant keys. Pops the top element on the stack which contains a tuple of keys, then starting from STACK[-2], pops count values to form values in the built dictionary.

Nuevo en la versión 3.6.

BUILD_STRING(count)

Concatena count cadenas de caracteres de la pila y empuja la cadena de caracteres resultante en la pila.

Nuevo en la versión 3.6.

LIST_EXTEND(i)

Implements:

seq = STACK.pop()
list.extend(STACK[-i], seq)

Used to build lists.

Nuevo en la versión 3.9.

SET_UPDATE(i)

Implements:

seq = STACK.pop()
set.update(STACK[-i], seq)

Used to build sets.

Nuevo en la versión 3.9.

DICT_UPDATE(i)

Implements:

map = STACK.pop()
dict.update(STACK[-i], map)

Used to build dicts.

Nuevo en la versión 3.9.

DICT_MERGE(i)

Como DICT_UPDATE pero lanza una excepción para claves duplicadas.

Nuevo en la versión 3.9.

LOAD_ATTR(namei)

If the low bit of namei is not set, this replaces STACK[-1] with getattr(STACK[-1], co_names[namei>>1]).

If the low bit of namei is set, this will attempt to load a method named co_names[namei>>1] from the STACK[-1] object. STACK[-1] is popped. This bytecode distinguishes two cases: if STACK[-1] has a method with the correct name, the bytecode pushes the unbound method and STACK[-1]. STACK[-1] will be used as the first argument (self) by CALL or CALL_KW when calling the unbound method. Otherwise, NULL and the object returned by the attribute lookup are pushed.

Distinto en la versión 3.12: If the low bit of namei is set, then a NULL or self is pushed to the stack before the attribute or unbound method respectively.

LOAD_SUPER_ATTR(namei)

This opcode implements super(), both in its zero-argument and two-argument forms (e.g. super().method(), super().attr and super(cls, self).method(), super(cls, self).attr).

It pops three values from the stack (from top of stack down):

  • self: the first argument to the current method

  • cls: the class within which the current method was defined

  • the global super

With respect to its argument, it works similarly to LOAD_ATTR, except that namei is shifted left by 2 bits instead of 1.

The low bit of namei signals to attempt a method load, as with LOAD_ATTR, which results in pushing NULL and the loaded method. When it is unset a single value is pushed to the stack.

The second-low bit of namei, if set, means that this was a two-argument call to super() (unset means zero-argument).

Nuevo en la versión 3.12.

COMPARE_OP(opname)

Performs a Boolean operation. The operation name can be found in cmp_op[opname >> 5]. If the fifth-lowest bit of opname is set (opname & 16), the result should be coerced to bool.

Distinto en la versión 3.13: The fifth-lowest bit of the oparg now indicates a forced conversion to bool.

IS_OP(invert)

Realiza una comparación is o is not si invert es 1.

Nuevo en la versión 3.9.

CONTAINS_OP(invert)

Realiza una comparación in o not in si invert es 1.

Nuevo en la versión 3.9.

IMPORT_NAME(namei)

Imports the module co_names[namei]. STACK[-1] and STACK[-2] are popped and provide the fromlist and level arguments of __import__(). The module object is pushed onto the stack. The current namespace is not affected: for a proper import statement, a subsequent STORE_FAST instruction modifies the namespace.

IMPORT_FROM(namei)

Loads the attribute co_names[namei] from the module found in STACK[-1]. The resulting object is pushed onto the stack, to be subsequently stored by a STORE_FAST instruction.

JUMP_FORWARD(delta)

Incrementa el contador de bytecode en delta.

JUMP_BACKWARD(delta)

Decrementa el contador de bytecode en delta. Comprueba si hay interrupciones.

Nuevo en la versión 3.11.

JUMP_BACKWARD_NO_INTERRUPT(delta)

Decrementa el contador de bytecode en delta. No busca interrupciones.

Nuevo en la versión 3.11.

POP_JUMP_IF_TRUE(delta)

If STACK[-1] is true, increments the bytecode counter by delta. STACK[-1] is popped.

Distinto en la versión 3.11: The oparg is now a relative delta rather than an absolute target. This opcode is a pseudo-instruction, replaced in final bytecode by the directed versions (forward/backward).

Distinto en la versión 3.12: This is no longer a pseudo-instruction.

Distinto en la versión 3.13: This instruction now requires an exact bool operand.

POP_JUMP_IF_FALSE(delta)

If STACK[-1] is false, increments the bytecode counter by delta. STACK[-1] is popped.

Distinto en la versión 3.11: The oparg is now a relative delta rather than an absolute target. This opcode is a pseudo-instruction, replaced in final bytecode by the directed versions (forward/backward).

Distinto en la versión 3.12: This is no longer a pseudo-instruction.

Distinto en la versión 3.13: This instruction now requires an exact bool operand.

POP_JUMP_IF_NOT_NONE(delta)

If STACK[-1] is not None, increments the bytecode counter by delta. STACK[-1] is popped.

This opcode is a pseudo-instruction, replaced in final bytecode by the directed versions (forward/backward).

Nuevo en la versión 3.11.

Distinto en la versión 3.12: This is no longer a pseudo-instruction.

POP_JUMP_IF_NONE(delta)

If STACK[-1] is None, increments the bytecode counter by delta. STACK[-1] is popped.

This opcode is a pseudo-instruction, replaced in final bytecode by the directed versions (forward/backward).

Nuevo en la versión 3.11.

Distinto en la versión 3.12: This is no longer a pseudo-instruction.

FOR_ITER(delta)

STACK[-1] is an iterator. Call its __next__() method. If this yields a new value, push it on the stack (leaving the iterator below it). If the iterator indicates it is exhausted then the byte code counter is incremented by delta.

Distinto en la versión 3.12: Up until 3.11 the iterator was popped when it was exhausted.

LOAD_GLOBAL(namei)

Carga el co_names[namei>>1] global llamado en la pila.

Distinto en la versión 3.11: Si se establece el bit bajo de namei, se agrega un NULL a la pila antes de la variable global.

LOAD_FAST(var_num)

Apila una referencia al local co_varnames[var_num] sobre la pila.

Distinto en la versión 3.12: This opcode is now only used in situations where the local variable is guaranteed to be initialized. It cannot raise UnboundLocalError.

LOAD_FAST_CHECK(var_num)

Pushes a reference to the local co_varnames[var_num] onto the stack, raising an UnboundLocalError if the local variable has not been initialized.

Nuevo en la versión 3.12.

LOAD_FAST_AND_CLEAR(var_num)

Pushes a reference to the local co_varnames[var_num] onto the stack (or pushes NULL onto the stack if the local variable has not been initialized) and sets co_varnames[var_num] to NULL.

Nuevo en la versión 3.12.

STORE_FAST(var_num)

Stores STACK.pop() into the local co_varnames[var_num].

DELETE_FAST(var_num)

Elimina la co_varnames[var_num] local.

MAKE_CELL(i)

Creates a new cell in slot i. If that slot is nonempty then that value is stored into the new cell.

Nuevo en la versión 3.11.

LOAD_DEREF(i)

Carga la celda contenida en el slot i del almacenamiento «fast locals». Agrega una referencia al objeto que contiene la celda en la pila.

Distinto en la versión 3.11: i is no longer offset by the length of co_varnames.

LOAD_FROM_DICT_OR_DEREF(i)

Pops a mapping off the stack and looks up the name associated with slot i of the «fast locals» storage in this mapping. If the name is not found there, loads it from the cell contained in slot i, similar to LOAD_DEREF. This is used for loading free variables in class bodies (which previously used LOAD_CLASSDEREF) and in annotation scopes within class bodies.

Nuevo en la versión 3.12.

STORE_DEREF(i)

Stores STACK.pop() into the cell contained in slot i of the «fast locals» storage.

Distinto en la versión 3.11: i is no longer offset by the length of co_varnames.

DELETE_DEREF(i)

Vacía la celda contenida en la ranura i del almacenamiento de «locales rápidos». Utilizado por la instrucción del.

Nuevo en la versión 3.2.

Distinto en la versión 3.11: i is no longer offset by the length of co_varnames.

COPY_FREE_VARS(n)

Copia las variables libres n del cierre al marco. Elimina la necesidad de un código especial en el lado del que llama al llamar clausuras.

Nuevo en la versión 3.11.

RAISE_VARARGS(argc)

Provoca una excepción utilizando una de las 3 formas de la declaración raise, dependiendo del valor de argc:

  • 0: raise (vuelve a lanzar la excepción anterior)

  • 1: raise STACK[-1] (raise exception instance or type at STACK[-1])

  • 2: raise STACK[-2] from STACK[-1] (raise exception instance or type at STACK[-2] with __cause__ set to STACK[-1])

CALL(argc)

Calls a callable object with the number of arguments specified by argc. On the stack are (in ascending order):

  • El llamable

  • self or NULL

  • Los argumentos posicionales restantes

argc is the total of the positional arguments, excluding self.

CALL extrae todos los argumentos y el objeto invocable de la pila, llama al objeto invocable con esos argumentos y agrega el valor retornado por el objeto invocable.

Nuevo en la versión 3.11.

Distinto en la versión 3.13: The callable now always appears at the same position on the stack.

Distinto en la versión 3.13: Calls with keyword arguments are now handled by CALL_KW.

CALL_KW(argc)

Calls a callable object with the number of arguments specified by argc, including one or more named arguments. On the stack are (in ascending order):

  • El llamable

  • self or NULL

  • Los argumentos posicionales restantes

  • Los argumentos nombrados

  • A tuple of keyword argument names

argc is the total of the positional and named arguments, excluding self. The length of the tuple of keyword argument names is the number of named arguments.

CALL_KW pops all arguments, the keyword names, and the callable object off the stack, calls the callable object with those arguments, and pushes the return value returned by the callable object.

Nuevo en la versión 3.13.

CALL_FUNCTION_EX(flags)

Llama a un objeto invocable con un conjunto variable de argumentos posicionales y de palabras clave. Si se establece el bit más bajo de flags, la parte superior de la pila contiene un objeto de mapeo que contiene argumentos de palabras clave adicionales. Antes de que se llame al invocable, el objeto de mapeo y el objeto iterable se «desempaquetan» y su contenido se pasa como palabra clave y argumentos posicionales, respectivamente. CALL_FUNCTION_EX saca todos los argumentos y el objeto invocable de la pila, llama al objeto invocable con esos argumentos y empuja el valor de retorno retornado por el objeto invocable.

Nuevo en la versión 3.6.

PUSH_NULL

Agrega un NULL a la pila. Se usa en la secuencia de llamadas para hacer coincidir el NULL enviado por LOAD_METHOD para llamadas que no son de método.

Nuevo en la versión 3.11.

MAKE_FUNCTION

Pushes a new function object on the stack built from the code object at STACK[1].

Distinto en la versión 3.10: El valor indicador 0x04 es una tupla de cadena de caracteres en vez de un diccionario

Distinto en la versión 3.11: Qualified name at STACK[-1] was removed.

Distinto en la versión 3.13: Extra function attributes on the stack, signaled by oparg flags, were removed. They now use SET_FUNCTION_ATTRIBUTE.

SET_FUNCTION_ATTRIBUTE(flag)

Sets an attribute on a function object. Expects the function at STACK[-1] and the attribute value to set at STACK[-2]; consumes both and leaves the function at STACK[-1]. The flag determines which attribute to set:

  • 0x01, una tupla de valores predeterminados para solo parámetros posicionales y posicionales o de palabras clave en orden posicional

  • 0x02 un diccionario de valores predeterminados de solo palabras clave

  • 0x04 una tupla de cadenas de caracteres que contiene anotaciones de parámetros

  • 0x08 una tupla que contiene celdas para variables libres, haciendo un cierre (closure)

Nuevo en la versión 3.13.

BUILD_SLICE(argc)

Pushes a slice object on the stack. argc must be 2 or 3. If it is 2, implements:

end = STACK.pop()
start = STACK.pop()
STACK.append(slice(start, stop))

if it is 3, implements:

step = STACK.pop()
end = STACK.pop()
start = STACK.pop()
STACK.append(slice(start, end, step))

See the slice() built-in function for more information.

EXTENDED_ARG(ext)

Prefija cualquier código de operación que tenga un argumento demasiado grande para caber en el byte predeterminado. ext contiene un byte adicional que actúa como bits más altos en el argumento. Para cada opcode, como máximo se permiten tres prefijos EXTENDED_ARG, formando un argumento de dos bytes a cuatro bytes.

CONVERT_VALUE(oparg)

Convert value to a string, depending on oparg:

value = STACK.pop()
result = func(value)
STACK.append(result)
  • oparg == 1: call str() on value

  • oparg == 2: call repr() on value

  • oparg == 3: call ascii() on value

Used for implementing formatted literal strings (f-strings).

Nuevo en la versión 3.13.

FORMAT_SIMPLE

Formats the value on top of stack:

value = STACK.pop()
result = value.__format__("")
STACK.append(result)

Used for implementing formatted literal strings (f-strings).

Nuevo en la versión 3.13.

FORMAT_SPEC

Formats the given value with the given format spec:

spec = STACK.pop()
value = STACK.pop()
result = value.__format__(spec)
STACK.append(result)

Used for implementing formatted literal strings (f-strings).

Nuevo en la versión 3.13.

MATCH_CLASS(count)

STACK[-1] is a tuple of keyword attribute names, STACK[-2] is the class being matched against, and STACK[-3] is the match subject. count is the number of positional sub-patterns.

Pop STACK[-1], STACK[-2], and STACK[-3]. If STACK[-3] is an instance of STACK[-2] and has the positional and keyword attributes required by count and STACK[-1], push a tuple of extracted attributes. Otherwise, push None.

Nuevo en la versión 3.10.

Distinto en la versión 3.11: Anteriormente, esta instrucción también generaba un valor booleano que indicaba éxito (True) o falla (False).

RESUME(context)

Un no-op. Realiza comprobaciones internas de seguimiento, depuración y optimización.

The context oparand consists of two parts. The lowest two bits indicate where the RESUME occurs:

  • 0 The start of a function, which is neither a generator, coroutine nor an async generator

  • 1 Después de una expresión yield

  • 2 Después de una expresión yield from

  • 3 Después de una expresión await

The next bit is 1 if the RESUME is at except-depth 1, and 0 otherwise.

Nuevo en la versión 3.11.

Distinto en la versión 3.13: The oparg value changed to include information about except-depth

RETURN_GENERATOR

Create a generator, coroutine, or async generator from the current frame. Used as first opcode of in code object for the above mentioned callables. Clear the current frame and return the newly created generator.

Nuevo en la versión 3.11.

SEND(delta)

Equivalent to STACK[-1] = STACK[-2].send(STACK[-1]). Used in yield from and await statements.

If the call raises StopIteration, pop the top value from the stack, push the exception’s value attribute, and increment the bytecode counter by delta.

Nuevo en la versión 3.11.

HAVE_ARGUMENT

This is not really an opcode. It identifies the dividing line between opcodes in the range [0,255] which don’t use their argument and those that do (< HAVE_ARGUMENT and >= HAVE_ARGUMENT, respectively).

If your application uses pseudo instructions or specialized instructions, use the hasarg collection instead.

Distinto en la versión 3.6: Ahora cada instrucción tiene un argumento, pero los códigos de operación <HAVE_ARGUMENT la ignoran. Antes, solo los códigos de operación > = HAVE_ARGUMENT tenían un argumento.

Distinto en la versión 3.12: Pseudo instructions were added to the dis module, and for them it is not true that comparison with HAVE_ARGUMENT indicates whether they use their arg.

Obsoleto desde la versión 3.13: Use hasarg instead.

CALL_INTRINSIC_1

Calls an intrinsic function with one argument. Passes STACK[-1] as the argument and sets STACK[-1] to the result. Used to implement functionality that is not performance critical.

The operand determines which intrinsic function is called:

Operand

Description

INTRINSIC_1_INVALID

Not valid

INTRINSIC_PRINT

Prints the argument to standard out. Used in the REPL.

INTRINSIC_IMPORT_STAR

Performs import * for the named module.

INTRINSIC_STOPITERATION_ERROR

Extracts the return value from a StopIteration exception.

INTRINSIC_ASYNC_GEN_WRAP

Wraps an aync generator value

INTRINSIC_UNARY_POSITIVE

Performs the unary + operation

INTRINSIC_LIST_TO_TUPLE

Converts a list to a tuple

INTRINSIC_TYPEVAR

Creates a typing.TypeVar

INTRINSIC_PARAMSPEC

Creates a typing.ParamSpec

INTRINSIC_TYPEVARTUPLE

Creates a typing.TypeVarTuple

INTRINSIC_SUBSCRIPT_GENERIC

Returns typing.Generic subscripted with the argument

INTRINSIC_TYPEALIAS

Creates a typing.TypeAliasType; used in the type statement. The argument is a tuple of the type alias’s name, type parameters, and value.

Nuevo en la versión 3.12.

CALL_INTRINSIC_2

Calls an intrinsic function with two arguments. Used to implement functionality that is not performance critical:

arg2 = STACK.pop()
arg1 = STACK.pop()
result = intrinsic2(arg1, arg2)
STACK.append(result)

The operand determines which intrinsic function is called:

Operand

Description

INTRINSIC_2_INVALID

Not valid

INTRINSIC_PREP_RERAISE_STAR

Calculates the ExceptionGroup to raise from a try-except*.

INTRINSIC_TYPEVAR_WITH_BOUND

Creates a typing.TypeVar with a bound.

INTRINSIC_TYPEVAR_WITH_CONSTRAINTS

Creates a typing.TypeVar with constraints.

INTRINSIC_SET_FUNCTION_TYPE_PARAMS

Sets the __type_params__ attribute of a function.

Nuevo en la versión 3.12.

Pseudo-instructions

These opcodes do not appear in Python bytecode. They are used by the compiler but are replaced by real opcodes or removed before bytecode is generated.

SETUP_FINALLY(target)

Set up an exception handler for the following code block. If an exception occurs, the value stack level is restored to its current state and control is transferred to the exception handler at target.

SETUP_CLEANUP(target)

Like SETUP_FINALLY, but in case of an exception also pushes the last instruction (lasti) to the stack so that RERAISE can restore it. If an exception occurs, the value stack level and the last instruction on the frame are restored to their current state, and control is transferred to the exception handler at target.

SETUP_WITH(target)

Like SETUP_CLEANUP, but in case of an exception one more item is popped from the stack before control is transferred to the exception handler at target.

This variant is used in with and async with constructs, which push the return value of the context manager’s __enter__() or __aenter__() to the stack.

POP_BLOCK

Marks the end of the code block associated with the last SETUP_FINALLY, SETUP_CLEANUP or SETUP_WITH.

JUMP
JUMP_NO_INTERRUPT

Undirected relative jump instructions which are replaced by their directed (forward/backward) counterparts by the assembler.

LOAD_CLOSURE(i)

Pushes a reference to the cell contained in slot i of the «fast locals» storage.

Note that LOAD_CLOSURE is replaced with LOAD_FAST in the assembler.

Distinto en la versión 3.13: This opcode is now a pseudo-instruction.

LOAD_METHOD

Optimized unbound method lookup. Emitted as a LOAD_ATTR opcode with a flag set in the arg.

Colecciones opcode

Estas colecciones se proporcionan para la introspección automática de instrucciones de bytecode:

Distinto en la versión 3.12: The collections now contain pseudo instructions and instrumented instructions as well. These are opcodes with values >= MIN_PSEUDO_OPCODE and >= MIN_INSTRUMENTED_OPCODE.

dis.opname

Secuencia de nombres de operaciones, indexable utilizando el bytecode.

dis.opmap

Nombres de operaciones de mapeo de diccionario a bytecodes.

dis.cmp_op

Secuencia de todos los nombres de operaciones de comparación.

dis.hasarg

Sequence of bytecodes that use their argument.

Nuevo en la versión 3.12.

dis.hasconst

Secuencia de bytecodes que acceden a una constante.

dis.hasfree

Sequence of bytecodes that access a free variable. “free” in this context refers to names in the current scope that are referenced by inner scopes or names in outer scopes that are referenced from this scope. It does not include references to global or builtin scopes.

dis.hasname

Secuencia de bytecodes que acceden a un atributo por nombre.

dis.hasjump

Sequence of bytecodes that have a jump target. All jumps are relative.

Nuevo en la versión 3.13.

dis.haslocal

Secuencia de códigos de bytes que acceden a una variable local.

dis.hascompare

Secuencia de bytecodes de operaciones booleanas.

dis.hasexc

Sequence of bytecodes that set an exception handler.

Nuevo en la versión 3.12.

dis.hasjrel

Secuencia de bytecodes que tienen un objetivo de salto relativo.

Obsoleto desde la versión 3.13: All jumps are now relative. Use hasjump.

dis.hasjabs

Secuencia de bytecodes que tienen un objetivo de salto absoluto.

Obsoleto desde la versión 3.13: All jumps are now relative. This list is empty.