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: The argument of jump, exception handling and loop instructions is now the instruction offset rather than the byte offset.
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
.
Ejemplo: dada la función myfunc()
:
def myfunc(alist):
return len(alist)
the following command can be used to display the disassembly of
myfunc()
:
>>> dis.dis(myfunc)
2 0 RESUME 0
3 2 LOAD_GLOBAL 1 (NULL + len)
14 LOAD_FAST 0 (alist)
16 CALL 1
26 RETURN_VALUE
(El «2» es un número de línea).
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)¶
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 deBytecode
produce las operaciones de bytecode como instancias deInstruction
.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 significadis()
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.- 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.
Example:
>>> 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)¶
Desmontar el objeto x. x puede denotar un módulo, una clase, un método, una función, un generador, un generador asíncrono, una corutina, un objeto de código, una cadena de código fuente o una secuencia de bytes de código de bytes sin procesar. Para un módulo, desmonta todas las funciones. Para una clase, desmonta todos los métodos (incluidos los métodos de clase y estáticos). Para un objeto de código o secuencia de bytecode sin procesar, imprime una línea por instrucción de bytecode. También desmonta recursivamente objetos de código anidados (el código de comprensiones, expresiones generadoras y funciones anidadas, y el código utilizado para construir clases anidadas). Las cadenas de caracteres se compilan primero en objetos de código con la función incorporada
compile()
antes de desmontarse. Si no se proporciona ningún objeto, esta función desmonta el último rastreo.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.
- dis.distb(tb=None, *, file=None, show_caches=False, adaptive=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.
- dis.disassemble(code, lasti=- 1, *, file=None, show_caches=False, adaptive=False)¶
- dis.disco(code, lasti=- 1, *, file=None, show_caches=False, adaptive=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:
el número de línea, para la primera instrucción de cada línea
la instrucción actual, indicada como
-->
,una instrucción etiquetada, indicada con
>>
,la dirección de la instrucción,
el nombre del código de operación,
parámetros de operación, y
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.
- 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 show_caches and adaptive parameters work as they do in
dis()
.Nuevo en la versión 3.4.
Distinto en la versión 3.11: Added the show_caches and adaptive parameters.
- 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 theco_firstlineno
andco_lnotab
attributes of the code object.
- 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 esFalse
, retornará el efecto de acumulación de no saltar. Y si jump esNone
(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.
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
- arg¶
argumento numérico para la operación (si existe), de lo contrario
None
- argval¶
resolved arg value (if any), otherwise
None
- argrepr¶
human readable description of operation argument (if any), otherwise an empty string.
- offset¶
índice de inicio de operación dentro de la secuencia de bytecode
- starts_line¶
línea iniciada por este código de operación (si existe), de lo contrario
None
- is_jump_target¶
True
si otro código salta aquí, de lo contrario,False
- positions¶
dis.Positions
object holding the start and end locations that are covered by this instruction.
Nuevo en la versión 3.4.
Distinto en la versión 3.11: Field
positions
is added.
- class dis.Positions¶
In case the information is not available, some fields might be
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¶
Do nothing code. Used as a placeholder by the bytecode optimizer, and to generate line tracing events.
- POP_TOP¶
Removes the top-of-stack item.:
STACK.pop()
- END_FOR¶
Removes the top two values from the stack. Equivalent to POP_TOP; POP_TOP. Used to clean up at the end of loops, hence the name.
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¶
Rather than being an actual instruction, this opcode is used to mark extra space for the interpreter to cache useful data directly in the bytecode itself. It is automatically hidden by all
dis
utilities, but can be viewed withshow_caches=True
.Logically, this space is part of the preceding instruction. Many opcodes expect to be followed by an exact number of caches, and will instruct the interpreter to skip over them at runtime.
Populated caches can look like arbitrary instructions, so great care should be taken when reading or modifying raw, adaptive bytecode containing quickened data.
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]
.
- 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, implementsSTACK[-1] = iter(STACK[-1])
.Nuevo en la versión 3.5.
Binary and in-place operations
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[index])
- 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])
, whereget_awaitable(o)
returnso
ifo
is a coroutine object or a generator object with the CO_ITERABLE_COROUTINE flag, or resolveso.__await__
.If the
where
operand is nonzero, it indicates where the instruction occurs: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: Previously, this instruction did not have an 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. SeeGET_AWAITABLE
for details aboutget_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. IfSTACK[-1]
isStopAsyncIteration
pop 3 values from the stack and restore the exception state using the second of them. Otherwise re-raise the exception using the value from the stack. An exception handler block is removed from the block stack.Nuevo en la versión 3.8:
Distinto en la versión 3.11: Exception representation on the stack now consist of one, not three, items.
- CLEANUP_THROW¶
Handles an exception raised during a
throw()
orclose()
call through the current frame. IfSTACK[-1]
is an instance ofStopIteration
, pop three values from the stack and push itsvalue
member. Otherwise, re-raiseSTACK[-1]
.Nuevo en la versión 3.12.
- BEFORE_ASYNC_WITH¶
Resolves
__aenter__
and__aexit__
fromSTACK[-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 isSTACK[-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.
- 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.
- SETUP_ANNOTATIONS¶
Comprueba si
__anotaciones__
está definido enlocals()
, si no está configurado como undict
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¶
Pops a value from the stack, which is used to restore the exception state.
Distinto en la versión 3.11: Exception representation on the stack now consist of one, not three, items.
- 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: Exception representation on the stack now consist of one, not three, items.
- PUSH_EXC_INFO¶
Pops a value from the stack. Pushes the current exception to the top of the stack. Pushes the value originally popped back to the stack. Used in exception handlers.
Nuevo en la versión 3.11.
- CHECK_EXC_MATCH¶
Performs exception matching for
except
. Tests whether theSTACK[-2]
is an exception matchingSTACK[-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*
. Appliessplit(STACK[-1])
on the exception group representingSTACK[-2]
.In case of a match, pops two items from the stack and pushes the non-matching subgroup (
None
in case of full match) followed by the matching subgroup. When there is no match, pops one item (the match type) and pushesNone
.Nuevo en la versión 3.11.
- PREP_RERAISE_STAR¶
Combines the raised and reraised exceptions list from
STACK[-1]
, into an exception group to propagate from a try-except* block. Uses the original exception group fromSTACK[-2]
to reconstruct the structure of reraised exceptions. Pops two items from the stack and pushes the exception to reraise orNone
if there isn’t one.Nuevo en la versión 3.11.
- WITH_EXCEPT_START¶
Calls the function in position 4 on the stack with arguments (type, val, tb) representing the exception at the top of the stack. Used to implement the call
context_manager.__exit__(*exc_info())
when an exception has occurred in awith
statement.Nuevo en la versión 3.9.
Distinto en la versión 3.11: The
__exit__
function is in position 4 of the stack rather than 7. Exception representation on the stack now consist of one, not three, items.
- LOAD_ASSERTION_ERROR¶
Inserta
AssertionError
en la pila. Utilizado por la declaraciónassert
.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¶
This opcode performs several operations before a with block starts. First, it loads
__exit__()
from the context manager and pushes it onto the stack for later use byWITH_EXCEPT_START
. Then,__enter__()
is called. Finally, the result of calling the__enter__()
method is pushed onto the stack.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 ofcollections.abc.Mapping
(or, more technically: if it has thePy_TPFLAGS_MAPPING
flag set in itstp_flags
), pushTrue
onto the stack. Otherwise, pushFalse
.Nuevo en la versión 3.10.
- MATCH_SEQUENCE¶
If
STACK[-1]
is an instance ofcollections.abc.Sequence
and is not an instance ofstr
/bytes
/bytearray
(or, more technically: if it has thePy_TPFLAGS_SEQUENCE
flag set in itstp_flags
), pushTrue
onto the stack. Otherwise, pushFalse
.Nuevo en la versión 3.10.
- MATCH_KEYS¶
STACK[-1]
is a tuple of mapping keys, andSTACK[-2]
is the match subject. IfSTACK[-2]
contains all of the keys inSTACK[-1]
, push atuple
containing the corresponding values. Otherwise, pushNone
.Nuevo en la versión 3.10.
Distinto en la versión 3.11: Previously, this instruction also pushed a boolean value indicating success (
True
) or failure (False
).
- STORE_NAME(namei)¶
Implements
name = STACK.pop()
. namei is the index of name in the attributeco_names
of the code object. The compiler tries to useSTORE_FAST
orSTORE_GLOBAL
if possible.
- DELETE_NAME(namei)¶
Implementa
del name
, donde namei es el índice en atributoco_names
del objeto de código.
- UNPACK_SEQUENCE(count)¶
Unpacks
STACK[-1]
into count individual values, which are put onto the stack right-to-left.:STACK.extend(STACK.pop()[:count:-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 asSTACK.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
.
- DELETE_ATTR(namei)¶
Implements:
obj = STACK.pop() del obj.name
where namei is the index of name into
co_names
.
- 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)¶
Apila el valor asociado con
co_names [namei]
en la pila.
- 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 fromSTACK[-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 replacesSTACK[-1]
withgetattr(STACK[-1], co_names[namei>>1])
.If the low bit of
namei
is set, this will attempt to load a method namedco_names[namei>>1]
from theSTACK[-1]
object.STACK[-1]
is popped. This bytecode distinguishes two cases: ifSTACK[-1]
has a method with the correct name, the bytecode pushes the unbound method andSTACK[-1]
.STACK[-1]
will be used as the first argument (self
) byCALL
when calling the unbound method. Otherwise,NULL
and the object return by the attribute lookup are pushed.Distinto en la versión 3.12: If the low bit of
namei
is set, then aNULL
orself
is pushed to the stack before the attribute or unbound method respectively.
- COMPARE_OP(opname)¶
Realiza una operación booleana. El nombre de la operación se puede encontrar en
cmp_op[opname]
.
- COMPARE_AND_BRANCH(opname)¶
Compares the top two values on the stack, popping them, then branches. The direction and offset of the jump is embedded as a
POP_JUMP_IF_TRUE
orPOP_JUMP_IF_FALSE
instruction immediately following the cache.Nuevo en la versión 3.12.
- IS_OP(invert)¶
Realiza una comparación
is
ois not
siinvert
es 1.Nuevo en la versión 3.9.
- CONTAINS_OP(invert)¶
Realiza una comparación
in
onot in
siinvert
es 1.Nuevo en la versión 3.9.
- IMPORT_NAME(namei)¶
Imports the module
co_names[namei]
.STACK[-1]
andSTACK[-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 subsequentSTORE_FAST
instruction modifies the namespace.
- IMPORT_FROM(namei)¶
Loads the attribute
co_names[namei]
from the module found inSTACK[-1]
. The resulting object is pushed onto the stack, to be subsequently stored by aSTORE_FAST
instruction.
- JUMP_FORWARD(delta)¶
Incrementa el contador de bytecode en delta.
- JUMP_BACKWARD(delta)¶
Decrements bytecode counter by delta. Checks for interrupts.
Nuevo en la versión 3.11.
- JUMP_BACKWARD_NO_INTERRUPT(delta)¶
Decrements bytecode counter by delta. Does not check for interrupts.
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.
- 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.
- POP_JUMP_IF_NOT_NONE(delta)¶
If
STACK[-1]
is notNone
, 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]
isNone
, 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.
- JUMP_IF_TRUE_OR_POP(delta)¶
If
STACK[-1]
is true, increments the bytecode counter by delta and leavesSTACK[-1]
on the stack. Otherwise (STACK[-1]
is false),STACK[-1]
is popped.Nuevo en la versión 3.1.
Distinto en la versión 3.11: The oparg is now a relative delta rather than an absolute target.
- JUMP_IF_FALSE_OR_POP(delta)¶
If
STACK[-1]
is false, increments the bytecode counter by delta and leavesSTACK[-1]
on the stack. Otherwise (STACK[-1]
is true),STACK[-1]
is popped.Nuevo en la versión 3.1.
Distinto en la versión 3.11: The oparg is now a relative delta rather than an absolute target.
- 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)¶
Loads the global named
co_names[namei>>1]
onto the stack.Distinto en la versión 3.11: If the low bit of
namei
is set, then aNULL
is pushed to the stack before the global variable.
- 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 anUnboundLocalError
if the local variable has not been initialized.Nuevo en la versión 3.12.
- STORE_FAST(var_num)¶
Stores
STACK.pop()
into the localco_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 empty then that value is stored into the new cell.Nuevo en la versión 3.11.
- LOAD_CLOSURE(i)¶
Pushes a reference to the cell contained in slot
i
of the «fast locals» storage. The name of the variable isco_fastlocalnames[i]
.Note that
LOAD_CLOSURE
is effectively an alias forLOAD_FAST
. It exists to keep bytecode a little more readable.Distinto en la versión 3.11:
i
is no longer offset by the length ofco_varnames
.
- LOAD_DEREF(i)¶
Loads the cell contained in slot
i
of the «fast locals» storage. Pushes a reference to the object the cell contains on the stack.Distinto en la versión 3.11:
i
is no longer offset by the length ofco_varnames
.
- LOAD_CLASSDEREF(i)¶
Al igual que
LOAD_DEREF
pero primero verifica el diccionario local antes de consultar la celda. Esto se usa para cargar variables libres en los cuerpos de clase.Nuevo en la versión 3.4.
Distinto en la versión 3.11:
i
is no longer offset by the length ofco_varnames
.
- STORE_DEREF(i)¶
Stores
STACK.pop()
into the cell contained in sloti
of the «fast locals» storage.Distinto en la versión 3.11:
i
is no longer offset by the length ofco_varnames
.
- DELETE_DEREF(i)¶
Empties the cell contained in slot
i
of the «fast locals» storage. Used by thedel
statement.Nuevo en la versión 3.2.
Distinto en la versión 3.11:
i
is no longer offset by the length ofco_varnames
.
- COPY_FREE_VARS(n)¶
Copies the
n
free variables from the closure into the frame. Removes the need for special code on the caller’s side when calling closures.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 atSTACK[-1]
)2:
raise STACK[-2] from STACK[-1]
(raise exception instance or type atSTACK[-2]
with__cause__
set toSTACK[-1]
)
- CALL(argc)¶
Calls a callable object with the number of arguments specified by
argc
, including the named arguments specified by the precedingKW_NAMES
, if any. On the stack are (in ascending order), either:NULL
The callable
The positional arguments
The named arguments
or:
The callable
self
The remaining positional arguments
The named arguments
argc
is the total of the positional and named arguments, excludingself
when aNULL
is not present.CALL
pops all arguments 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.11.
- 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 devuelto por el objeto invocable.Nuevo en la versión 3.6.
- PUSH_NULL¶
Pushes a
NULL
to the stack. Used in the call sequence to match theNULL
pushed byLOAD_METHOD
for non-method calls.Nuevo en la versión 3.11.
- KW_NAMES(consti)¶
Prefixes
CALL
. Stores a reference toco_consts[consti]
into an internal variable for use byCALL
.co_consts[consti]
must be a tuple of strings.Nuevo en la versión 3.11.
- MAKE_FUNCTION(flags)¶
Apila un nuevo objeto de función en la pila. De abajo hacia arriba, la pila consumida debe constar de valores si el argumento lleva un valor de marca especificado
0x01
, una tupla de valores predeterminados para solo parámetros posicionales y posicionales o de palabras clave en orden posicional0x02
un diccionario de valores predeterminados de solo palabras clave0x04
una tupla de cadenas de caracteres que contiene anotaciones de parámetros0x08
una tupla que contiene celdas para variables libres, haciendo un cierre (closure)the code associated with the function (at
STACK[-2]
)the qualified name of the function (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
- 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.
- FORMAT_VALUE(flags)¶
Se utiliza para implementar cadenas literales formateadas (cadenas de caracteres f). Desapila un fmt_spec opcional de la pila, luego un value requerido. flags se interpreta de la siguiente manera:
(flags & 0x03) == 0x00
: value es formateado como está.(flags & 0x03) == 0x01
: llamastr()
sobre value antes de formatearlo.(flags & 0x03) == 0x02
: llamarepr()
sobre value antes de formatearlo.(flags & 0x03) == 0x03
: llamaascii()
sobre value antes de formatearlo.(flags & 0x04) == 0x04
: desapila fmt_spec de la pila y lo usa, de lo contrario usa un fmt_spec vacío.
El formateo se realiza usando
PyObject_Format()
. El resultado se apila en la pila.Nuevo en la versión 3.6.
- MATCH_CLASS(count)¶
STACK[-1]
is a tuple of keyword attribute names,STACK[-2]
is the class being matched against, andSTACK[-3]
is the match subject. count is the number of positional sub-patterns.Pop
STACK[-1]
,STACK[-2]
, andSTACK[-3]
. IfSTACK[-3]
is an instance ofSTACK[-2]
and has the positional and keyword attributes required by count andSTACK[-1]
, push a tuple of extracted attributes. Otherwise, pushNone
.Nuevo en la versión 3.10.
Distinto en la versión 3.11: Previously, this instruction also pushed a boolean value indicating success (
True
) or failure (False
).
- RESUME(where)¶
A no-op. Performs internal tracing, debugging and optimization checks.
The
where
operand marks where theRESUME
occurs:0
The start of a function, which is neither a generator, coroutine nor an async generator1
After ayield
expression2
After ayield from
expression3
After anawait
expression
Nuevo en la versión 3.11.
- 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 inyield from
andawait
statements.If the call raises
StopIteration
, pop both items, push the exception’svalue
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, 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 withHAVE_ARGUMENT
indicates whether they use their arg.
- CALL_INTRINSIC_1¶
Calls an intrinsic function with one argument. Passes
STACK[-1]
as the argument and setsSTACK[-1]
to the result. Used to implement functionality that is necessary but not performance critical.The operand determines which intrinsic function is called:
0
Not valid1
Prints the argument to standard out. Used in the REPL.2
Performsimport *
for the named module.3
Extracts the return value from aStopIteration
exception.4
Wraps an aync generator value5
Performs the unary+
operation6
Converts a list to a tuple
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 exception also pushes the last instruction (lasti
) to the stack so thatRERAISE
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 attarget
.
- SETUP_WITH(target)¶
Like
SETUP_CLEANUP
, but in case of exception one more item is popped from the stack before control is transferred to the exception handler attarget
.This variant is used in
with
andasync 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
orSETUP_WITH
.
- JUMP¶
- JUMP_NO_INTERRUPT¶
Undirected relative jump instructions which are replaced by their directed (forward/backward) counterparts by the assembler.
- 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 as well. These are opcodes with values
>= MIN_PSEUDO_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¶
Secuencia de bytecodes que acceden a una variable libre (tenga en cuenta que “libre” en este contexto se refiere a nombres en el alcance actual a los que hacen referencia los ámbitos internos o los nombres en los ámbitos externos a los que se hace referencia desde este ámbito. No incluye referencias a ámbitos globales o integrados).
- dis.hasname¶
Secuencia de bytecodes que acceden a un atributo por nombre.
- dis.hasjrel¶
Secuencia de bytecodes que tienen un objetivo de salto relativo.
- dis.hasjabs¶
Secuencia de bytecodes que tienen un objetivo de salto absoluto.
- 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.