cpython_sandbox / Doc / library / dis.rst

Full commit

:mod:`dis` --- Disassembler for Python bytecode

Source code: :source:`Lib/`

The :mod:`dis` module supports the analysis of CPython :term:`bytecode` by disassembling it. The CPython bytecode which this module takes as an input is defined in the file :file:`Include/opcode.h` and used by the compiler and the interpreter.

Example: Given the function :func:`myfunc`:

def myfunc(alist):
    return len(alist)

the following command can be used to display the disassembly of :func:`myfunc`:

>>> dis.dis(myfunc)
  2           0 LOAD_GLOBAL              0 (len)
              3 LOAD_FAST                0 (alist)
              6 CALL_FUNCTION            1
              9 RETURN_VALUE

(The "2" is a line number).

Bytecode analysis

The bytecode analysis API allows pieces of Python code to be wrapped in a :class:`Bytecode` object that provides easy access to details of the compiled code.

The bytecode operations of a piece of code

This is a convenient wrapper around many of the functions listed below. Instantiate it with a function, method, string of code, or a code object (as returned by :func:`compile`).

Iterating over this yields the bytecode operations as :class:`Instruction` instances.


>>> bytecode = dis.Bytecode(myfunc)
>>> for instr in bytecode:
...     print(instr.opname)

Analysis functions

The :mod:`dis` module also defines the following analysis functions that convert the input directly to the desired output. They can be useful if only a single operation is being performed, so the intermediate analysis object isn't useful:

Python Bytecode Instructions

The :func:`get_instructions` function and :class:`Bytecode` class provide details of bytecode instructions as :class:`Instruction` instances:

Details for a bytecode operation

The Python compiler currently generates the following bytecode instructions.

General instructions

Unary operations

Unary operations take the top of the stack, apply the operation, and push the result back on the stack.

Binary operations

Binary operations remove the top of the stack (TOS) and the second top-most stack item (TOS1) from the stack. They perform the operation, and put the result back on the stack.

In-place operations

In-place operations are like binary operations, in that they remove TOS and TOS1, and push the result back on the stack, but the operation is done in-place when TOS1 supports it, and the resulting TOS may be (but does not have to be) the original TOS1.

Miscellaneous opcodes

For all of the SET_ADD, LIST_APPEND and MAP_ADD instructions, while the added value or key/value pair is popped off, the container object remains on the stack so that it is available for further iterations of the loop.

All of the following opcodes expect arguments. An argument is two bytes, with the more significant byte last.

Opcode collections

These collections are provided for automatic introspection of bytecode instructions: