Added section on passing contextual information to logging and documentation for...
[python.git] / Doc / library / dis.rst
blob8236a9cd885d2e2f9f75f6f3f3a458a6c8af52f5
2 :mod:`dis` --- Disassembler for Python bytecode
3 ===============================================
5 .. module:: dis
6    :synopsis: Disassembler for Python bytecode.
9 The :mod:`dis` module supports the analysis of Python :term:`bytecode` by disassembling
10 it.  Since there is no Python assembler, this module defines the Python assembly
11 language.  The Python bytecode which this module takes as an input is defined
12 in the file  :file:`Include/opcode.h` and used by the compiler and the
13 interpreter.
15 Example: Given the function :func:`myfunc`::
17    def myfunc(alist):
18        return len(alist)
20 the following command can be used to get the disassembly of :func:`myfunc`::
22    >>> dis.dis(myfunc)
23      2           0 LOAD_GLOBAL              0 (len)
24                  3 LOAD_FAST                0 (alist)
25                  6 CALL_FUNCTION            1
26                  9 RETURN_VALUE
28 (The "2" is a line number).
30 The :mod:`dis` module defines the following functions and constants:
33 .. function:: dis([bytesource])
35    Disassemble the *bytesource* object. *bytesource* can denote either a module, a
36    class, a method, a function, or a code object.   For a module, it disassembles
37    all functions.  For a class, it disassembles all methods.  For a single code
38    sequence, it prints one line per bytecode instruction.  If no object is
39    provided, it disassembles the last traceback.
42 .. function:: distb([tb])
44    Disassembles the top-of-stack function of a traceback, using the last traceback
45    if none was passed.  The instruction causing the exception is indicated.
48 .. function:: disassemble(code[, lasti])
50    Disassembles a code object, indicating the last instruction if *lasti* was
51    provided.  The output is divided in the following columns:
53    #. the line number, for the first instruction of each line
54    #. the current instruction, indicated as ``-->``,
55    #. a labelled instruction, indicated with ``>>``,
56    #. the address of the instruction,
57    #. the operation code name,
58    #. operation parameters, and
59    #. interpretation of the parameters in parentheses.
61    The parameter interpretation recognizes local and global variable names,
62    constant values, branch targets, and compare operators.
65 .. function:: disco(code[, lasti])
67    A synonym for disassemble.  It is more convenient to type, and kept for
68    compatibility with earlier Python releases.
71 .. data:: opname
73    Sequence of operation names, indexable using the bytecode.
76 .. data:: opmap
78    Dictionary mapping bytecodes to operation names.
81 .. data:: cmp_op
83    Sequence of all compare operation names.
86 .. data:: hasconst
88    Sequence of bytecodes that have a constant parameter.
91 .. data:: hasfree
93    Sequence of bytecodes that access a free variable.
96 .. data:: hasname
98    Sequence of bytecodes that access an attribute by name.
101 .. data:: hasjrel
103    Sequence of bytecodes that have a relative jump target.
106 .. data:: hasjabs
108    Sequence of bytecodes that have an absolute jump target.
111 .. data:: haslocal
113    Sequence of bytecodes that access a local variable.
116 .. data:: hascompare
118    Sequence of bytecodes of Boolean operations.
121 .. _bytecodes:
123 Python Bytecode Instructions
124 ----------------------------
126 The Python compiler currently generates the following bytecode instructions.
129 .. opcode:: STOP_CODE ()
131    Indicates end-of-code to the compiler, not used by the interpreter.
134 .. opcode:: NOP ()
136    Do nothing code.  Used as a placeholder by the bytecode optimizer.
139 .. opcode:: POP_TOP ()
141    Removes the top-of-stack (TOS) item.
144 .. opcode:: ROT_TWO ()
146    Swaps the two top-most stack items.
149 .. opcode:: ROT_THREE ()
151    Lifts second and third stack item one position up, moves top down to position
152    three.
155 .. opcode:: ROT_FOUR ()
157    Lifts second, third and forth stack item one position up, moves top down to
158    position four.
161 .. opcode:: DUP_TOP ()
163    Duplicates the reference on top of the stack.
165 Unary Operations take the top of the stack, apply the operation, and push the
166 result back on the stack.
169 .. opcode:: UNARY_POSITIVE ()
171    Implements ``TOS = +TOS``.
174 .. opcode:: UNARY_NEGATIVE ()
176    Implements ``TOS = -TOS``.
179 .. opcode:: UNARY_NOT ()
181    Implements ``TOS = not TOS``.
184 .. opcode:: UNARY_CONVERT ()
186    Implements ``TOS = `TOS```.
189 .. opcode:: UNARY_INVERT ()
191    Implements ``TOS = ~TOS``.
194 .. opcode:: GET_ITER ()
196    Implements ``TOS = iter(TOS)``.
198 Binary operations remove the top of the stack (TOS) and the second top-most
199 stack item (TOS1) from the stack.  They perform the operation, and put the
200 result back on the stack.
203 .. opcode:: BINARY_POWER ()
205    Implements ``TOS = TOS1 ** TOS``.
208 .. opcode:: BINARY_MULTIPLY ()
210    Implements ``TOS = TOS1 * TOS``.
213 .. opcode:: BINARY_DIVIDE ()
215    Implements ``TOS = TOS1 / TOS`` when ``from __future__ import division`` is not
216    in effect.
219 .. opcode:: BINARY_FLOOR_DIVIDE ()
221    Implements ``TOS = TOS1 // TOS``.
224 .. opcode:: BINARY_TRUE_DIVIDE ()
226    Implements ``TOS = TOS1 / TOS`` when ``from __future__ import division`` is in
227    effect.
230 .. opcode:: BINARY_MODULO ()
232    Implements ``TOS = TOS1 % TOS``.
235 .. opcode:: BINARY_ADD ()
237    Implements ``TOS = TOS1 + TOS``.
240 .. opcode:: BINARY_SUBTRACT ()
242    Implements ``TOS = TOS1 - TOS``.
245 .. opcode:: BINARY_SUBSCR ()
247    Implements ``TOS = TOS1[TOS]``.
250 .. opcode:: BINARY_LSHIFT ()
252    Implements ``TOS = TOS1 << TOS``.
255 .. opcode:: BINARY_RSHIFT ()
257    Implements ``TOS = TOS1 >> TOS``.
260 .. opcode:: BINARY_AND ()
262    Implements ``TOS = TOS1 & TOS``.
265 .. opcode:: BINARY_XOR ()
267    Implements ``TOS = TOS1 ^ TOS``.
270 .. opcode:: BINARY_OR ()
272    Implements ``TOS = TOS1 | TOS``.
274 In-place operations are like binary operations, in that they remove TOS and
275 TOS1, and push the result back on the stack, but the operation is done in-place
276 when TOS1 supports it, and the resulting TOS may be (but does not have to be)
277 the original TOS1.
280 .. opcode:: INPLACE_POWER ()
282    Implements in-place ``TOS = TOS1 ** TOS``.
285 .. opcode:: INPLACE_MULTIPLY ()
287    Implements in-place ``TOS = TOS1 * TOS``.
290 .. opcode:: INPLACE_DIVIDE ()
292    Implements in-place ``TOS = TOS1 / TOS`` when ``from __future__ import
293    division`` is not in effect.
296 .. opcode:: INPLACE_FLOOR_DIVIDE ()
298    Implements in-place ``TOS = TOS1 // TOS``.
301 .. opcode:: INPLACE_TRUE_DIVIDE ()
303    Implements in-place ``TOS = TOS1 / TOS`` when ``from __future__ import
304    division`` is in effect.
307 .. opcode:: INPLACE_MODULO ()
309    Implements in-place ``TOS = TOS1 % TOS``.
312 .. opcode:: INPLACE_ADD ()
314    Implements in-place ``TOS = TOS1 + TOS``.
317 .. opcode:: INPLACE_SUBTRACT ()
319    Implements in-place ``TOS = TOS1 - TOS``.
322 .. opcode:: INPLACE_LSHIFT ()
324    Implements in-place ``TOS = TOS1 << TOS``.
327 .. opcode:: INPLACE_RSHIFT ()
329    Implements in-place ``TOS = TOS1 >> TOS``.
332 .. opcode:: INPLACE_AND ()
334    Implements in-place ``TOS = TOS1 & TOS``.
337 .. opcode:: INPLACE_XOR ()
339    Implements in-place ``TOS = TOS1 ^ TOS``.
342 .. opcode:: INPLACE_OR ()
344    Implements in-place ``TOS = TOS1 | TOS``.
346 The slice opcodes take up to three parameters.
349 .. opcode:: SLICE+0 ()
351    Implements ``TOS = TOS[:]``.
354 .. opcode:: SLICE+1 ()
356    Implements ``TOS = TOS1[TOS:]``.
359 .. opcode:: SLICE+2 ()
361    Implements ``TOS = TOS1[:TOS]``.
364 .. opcode:: SLICE+3 ()
366    Implements ``TOS = TOS2[TOS1:TOS]``.
368 Slice assignment needs even an additional parameter.  As any statement, they put
369 nothing on the stack.
372 .. opcode:: STORE_SLICE+0 ()
374    Implements ``TOS[:] = TOS1``.
377 .. opcode:: STORE_SLICE+1 ()
379    Implements ``TOS1[TOS:] = TOS2``.
382 .. opcode:: STORE_SLICE+2 ()
384    Implements ``TOS1[:TOS] = TOS2``.
387 .. opcode:: STORE_SLICE+3 ()
389    Implements ``TOS2[TOS1:TOS] = TOS3``.
392 .. opcode:: DELETE_SLICE+0 ()
394    Implements ``del TOS[:]``.
397 .. opcode:: DELETE_SLICE+1 ()
399    Implements ``del TOS1[TOS:]``.
402 .. opcode:: DELETE_SLICE+2 ()
404    Implements ``del TOS1[:TOS]``.
407 .. opcode:: DELETE_SLICE+3 ()
409    Implements ``del TOS2[TOS1:TOS]``.
412 .. opcode:: STORE_SUBSCR ()
414    Implements ``TOS1[TOS] = TOS2``.
417 .. opcode:: DELETE_SUBSCR ()
419    Implements ``del TOS1[TOS]``.
421 Miscellaneous opcodes.
424 .. opcode:: PRINT_EXPR ()
426    Implements the expression statement for the interactive mode.  TOS is removed
427    from the stack and printed.  In non-interactive mode, an expression statement is
428    terminated with ``POP_STACK``.
431 .. opcode:: PRINT_ITEM ()
433    Prints TOS to the file-like object bound to ``sys.stdout``.  There is one such
434    instruction for each item in the :keyword:`print` statement.
437 .. opcode:: PRINT_ITEM_TO ()
439    Like ``PRINT_ITEM``, but prints the item second from TOS to the file-like object
440    at TOS.  This is used by the extended print statement.
443 .. opcode:: PRINT_NEWLINE ()
445    Prints a new line on ``sys.stdout``.  This is generated as the last operation of
446    a :keyword:`print` statement, unless the statement ends with a comma.
449 .. opcode:: PRINT_NEWLINE_TO ()
451    Like ``PRINT_NEWLINE``, but prints the new line on the file-like object on the
452    TOS.  This is used by the extended print statement.
455 .. opcode:: BREAK_LOOP ()
457    Terminates a loop due to a :keyword:`break` statement.
460 .. opcode:: CONTINUE_LOOP (target)
462    Continues a loop due to a :keyword:`continue` statement.  *target* is the
463    address to jump to (which should be a ``FOR_ITER`` instruction).
466 .. opcode:: LIST_APPEND ()
468    Calls ``list.append(TOS1, TOS)``.  Used to implement list comprehensions.
471 .. opcode:: LOAD_LOCALS ()
473    Pushes a reference to the locals of the current scope on the stack. This is used
474    in the code for a class definition: After the class body is evaluated, the
475    locals are passed to the class definition.
478 .. opcode:: RETURN_VALUE ()
480    Returns with TOS to the caller of the function.
483 .. opcode:: YIELD_VALUE ()
485    Pops ``TOS`` and yields it from a :term:`generator`.
488 .. opcode:: IMPORT_STAR ()
490    Loads all symbols not starting with ``'_'`` directly from the module TOS to the
491    local namespace. The module is popped after loading all names. This opcode
492    implements ``from module import *``.
495 .. opcode:: EXEC_STMT ()
497    Implements ``exec TOS2,TOS1,TOS``.  The compiler fills missing optional
498    parameters with ``None``.
501 .. opcode:: POP_BLOCK ()
503    Removes one block from the block stack.  Per frame, there is a  stack of blocks,
504    denoting nested loops, try statements, and such.
507 .. opcode:: END_FINALLY ()
509    Terminates a :keyword:`finally` clause.  The interpreter recalls whether the
510    exception has to be re-raised, or whether the function returns, and continues
511    with the outer-next block.
514 .. opcode:: BUILD_CLASS ()
516    Creates a new class object.  TOS is the methods dictionary, TOS1 the tuple of
517    the names of the base classes, and TOS2 the class name.
520 .. opcode:: WITH_CLEANUP ()
522    Cleans up the stack when a :keyword:`with` statement block exits.  TOS is the
523    context manager's :meth:`__exit__` bound method.  Below that are 1--3 values
524    indicating how/why the finally clause was entered:
526    * SECOND = ``None``
527    * (SECOND, THIRD) = (``WHY_{RETURN,CONTINUE}``), retval
528    * SECOND = ``WHY_*``; no retval below it
529    * (SECOND, THIRD, FOURTH) = exc_info()
531    In the last case, ``TOS(SECOND, THIRD, FOURTH)`` is called, otherwise
532    ``TOS(None, None, None)``.
534    In addition, if the stack represents an exception, *and* the function call
535    returns a 'true' value, this information is "zapped", to prevent ``END_FINALLY``
536    from re-raising the exception.  (But non-local gotos should still be resumed.)
538    .. XXX explain the WHY stuff!
541 All of the following opcodes expect arguments.  An argument is two bytes, with
542 the more significant byte last.
544 .. opcode:: STORE_NAME (namei)
546    Implements ``name = TOS``. *namei* is the index of *name* in the attribute
547    :attr:`co_names` of the code object. The compiler tries to use ``STORE_LOCAL``
548    or ``STORE_GLOBAL`` if possible.
551 .. opcode:: DELETE_NAME (namei)
553    Implements ``del name``, where *namei* is the index into :attr:`co_names`
554    attribute of the code object.
557 .. opcode:: UNPACK_SEQUENCE (count)
559    Unpacks TOS into *count* individual values, which are put onto the stack
560    right-to-left.
563 .. opcode:: DUP_TOPX (count)
565    Duplicate *count* items, keeping them in the same order. Due to implementation
566    limits, *count* should be between 1 and 5 inclusive.
569 .. opcode:: STORE_ATTR (namei)
571    Implements ``TOS.name = TOS1``, where *namei* is the index of name in
572    :attr:`co_names`.
575 .. opcode:: DELETE_ATTR (namei)
577    Implements ``del TOS.name``, using *namei* as index into :attr:`co_names`.
580 .. opcode:: STORE_GLOBAL (namei)
582    Works as ``STORE_NAME``, but stores the name as a global.
585 .. opcode:: DELETE_GLOBAL (namei)
587    Works as ``DELETE_NAME``, but deletes a global name.
590 .. opcode:: LOAD_CONST (consti)
592    Pushes ``co_consts[consti]`` onto the stack.
595 .. opcode:: LOAD_NAME (namei)
597    Pushes the value associated with ``co_names[namei]`` onto the stack.
600 .. opcode:: BUILD_TUPLE (count)
602    Creates a tuple consuming *count* items from the stack, and pushes the resulting
603    tuple onto the stack.
606 .. opcode:: BUILD_LIST (count)
608    Works as ``BUILD_TUPLE``, but creates a list.
611 .. opcode:: BUILD_MAP (count)
613    Pushes a new dictionary object onto the stack.  The dictionary is pre-sized
614    to hold *count* entries.
617 .. opcode:: LOAD_ATTR (namei)
619    Replaces TOS with ``getattr(TOS, co_names[namei])``.
622 .. opcode:: COMPARE_OP (opname)
624    Performs a Boolean operation.  The operation name can be found in
625    ``cmp_op[opname]``.
628 .. opcode:: IMPORT_NAME (namei)
630    Imports the module ``co_names[namei]``.  The module object is pushed onto the
631    stack.  The current namespace is not affected: for a proper import statement, a
632    subsequent ``STORE_FAST`` instruction modifies the namespace.
635 .. opcode:: IMPORT_FROM (namei)
637    Loads the attribute ``co_names[namei]`` from the module found in TOS. The
638    resulting object is pushed onto the stack, to be subsequently stored by a
639    ``STORE_FAST`` instruction.
642 .. opcode:: JUMP_FORWARD (delta)
644    Increments bytecode counter by *delta*.
647 .. opcode:: JUMP_IF_TRUE (delta)
649    If TOS is true, increment the bytecode counter by *delta*.  TOS is left on the
650    stack.
653 .. opcode:: JUMP_IF_FALSE (delta)
655    If TOS is false, increment the bytecode counter by *delta*.  TOS is not
656    changed.
659 .. opcode:: JUMP_ABSOLUTE (target)
661    Set bytecode counter to *target*.
664 .. opcode:: FOR_ITER (delta)
666    ``TOS`` is an :term:`iterator`.  Call its :meth:`next` method.  If this
667    yields a new value, push it on the stack (leaving the iterator below it).  If
668    the iterator indicates it is exhausted ``TOS`` is popped, and the bytecode
669    counter is incremented by *delta*.
672 .. opcode:: LOAD_GLOBAL (namei)
674    Loads the global named ``co_names[namei]`` onto the stack.
677 .. opcode:: SETUP_LOOP (delta)
679    Pushes a block for a loop onto the block stack.  The block spans from the
680    current instruction with a size of *delta* bytes.
683 .. opcode:: SETUP_EXCEPT (delta)
685    Pushes a try block from a try-except clause onto the block stack. *delta* points
686    to the first except block.
689 .. opcode:: SETUP_FINALLY (delta)
691    Pushes a try block from a try-except clause onto the block stack. *delta* points
692    to the finally block.
694 .. opcode:: STORE_MAP ()
696    Store a key and value pair in a dictionary.  Pops the key and value while leaving
697    the dictionary on the stack.
699 .. opcode:: LOAD_FAST (var_num)
701    Pushes a reference to the local ``co_varnames[var_num]`` onto the stack.
704 .. opcode:: STORE_FAST (var_num)
706    Stores TOS into the local ``co_varnames[var_num]``.
709 .. opcode:: DELETE_FAST (var_num)
711    Deletes local ``co_varnames[var_num]``.
714 .. opcode:: LOAD_CLOSURE (i)
716    Pushes a reference to the cell contained in slot *i* of the cell and free
717    variable storage.  The name of the variable is  ``co_cellvars[i]`` if *i* is
718    less than the length of *co_cellvars*.  Otherwise it is  ``co_freevars[i -
719    len(co_cellvars)]``.
722 .. opcode:: LOAD_DEREF (i)
724    Loads the cell contained in slot *i* of the cell and free variable storage.
725    Pushes a reference to the object the cell contains on the stack.
728 .. opcode:: STORE_DEREF (i)
730    Stores TOS into the cell contained in slot *i* of the cell and free variable
731    storage.
734 .. opcode:: SET_LINENO (lineno)
736    This opcode is obsolete.
739 .. opcode:: RAISE_VARARGS (argc)
741    Raises an exception. *argc* indicates the number of parameters to the raise
742    statement, ranging from 0 to 3.  The handler will find the traceback as TOS2,
743    the parameter as TOS1, and the exception as TOS.
746 .. opcode:: CALL_FUNCTION (argc)
748    Calls a function.  The low byte of *argc* indicates the number of positional
749    parameters, the high byte the number of keyword parameters. On the stack, the
750    opcode finds the keyword parameters first.  For each keyword argument, the value
751    is on top of the key.  Below the keyword parameters, the positional parameters
752    are on the stack, with the right-most parameter on top.  Below the parameters,
753    the function object to call is on the stack.
756 .. opcode:: MAKE_FUNCTION (argc)
758    Pushes a new function object on the stack.  TOS is the code associated with the
759    function.  The function object is defined to have *argc* default parameters,
760    which are found below TOS.
763 .. opcode:: MAKE_CLOSURE (argc)
765    Creates a new function object, sets its *func_closure* slot, and pushes it on
766    the stack.  TOS is the code associated with the function, TOS1 the tuple
767    containing cells for the closure's free variables.  The function also has
768    *argc* default parameters, which are found below the cells.
771 .. opcode:: BUILD_SLICE (argc)
773    .. index:: builtin: slice
775    Pushes a slice object on the stack.  *argc* must be 2 or 3.  If it is 2,
776    ``slice(TOS1, TOS)`` is pushed; if it is 3, ``slice(TOS2, TOS1, TOS)`` is
777    pushed. See the :func:`slice` built-in function for more information.
780 .. opcode:: EXTENDED_ARG (ext)
782    Prefixes any opcode which has an argument too big to fit into the default two
783    bytes.  *ext* holds two additional bytes which, taken together with the
784    subsequent opcode's argument, comprise a four-byte argument, *ext* being the two
785    most-significant bytes.
788 .. opcode:: CALL_FUNCTION_VAR (argc)
790    Calls a function. *argc* is interpreted as in ``CALL_FUNCTION``. The top element
791    on the stack contains the variable argument list, followed by keyword and
792    positional arguments.
795 .. opcode:: CALL_FUNCTION_KW (argc)
797    Calls a function. *argc* is interpreted as in ``CALL_FUNCTION``. The top element
798    on the stack contains the keyword arguments dictionary,  followed by explicit
799    keyword and positional arguments.
802 .. opcode:: CALL_FUNCTION_VAR_KW (argc)
804    Calls a function. *argc* is interpreted as in ``CALL_FUNCTION``.  The top
805    element on the stack contains the keyword arguments dictionary, followed by the
806    variable-arguments tuple, followed by explicit keyword and positional arguments.
809 .. opcode:: HAVE_ARGUMENT ()
811    This is not really an opcode.  It identifies the dividing line between opcodes
812    which don't take arguments ``< HAVE_ARGUMENT`` and those which do ``>=
813    HAVE_ARGUMENT``.