Source code:Lib/dis.py
Thedis module supports the analysis of CPythonbytecode bydisassembling it. The CPython bytecode which this module takes as aninput is defined in the fileInclude/opcode.h and used by the compilerand the interpreter.
CPython implementation detail: Bytecode is an implementation detail of the CPython interpreter. Noguarantees are made that bytecode will not be added, removed, or changedbetween versions of Python. Use of this module should not be considered towork across Python VMs or Python releases.
Example: Given the functionmyfunc():
defmyfunc(alist):returnlen(alist)
the following command can be used to get the disassembly ofmyfunc():
>>>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).
Thedis module defines the following functions and constants:
Return a formatted multi-line string with detailed code object informationfor the supplied function, method, source code string or code object.
Note that the exact contents of code info strings are highly implementationdependent and they may change arbitrarily across Python VMs or Pythonreleases.
New in version 3.2.
Print detailed code object information for the supplied function, method,source code string or code object to stdout.
This is a convenient shorthand forprint(code_info(x)), intended forinteractive exploration at the interpreter prompt.
New in version 3.2.
Disassemble thex object.x can denote either a module, a class, amethod, a function, a code object, a string of source code or a byte sequenceof raw bytecode. For a module, it disassembles all functions. For a class,it disassembles all methods. For a code object or sequence of raw bytecode,it prints one line per bytecode instruction. Strings are first compiled tocode objects with thecompile() built-in function before beingdisassembled. If no object is provided, this function disassembles the lasttraceback.
Disassemble the top-of-stack function of a traceback, using the lasttraceback if none was passed. The instruction causing the exception isindicated.
Disassemble a code object, indicating the last instruction iflasti wasprovided. The output is divided in the following columns:
The parameter interpretation recognizes local and global variable names,constant values, branch targets, and compare operators.
This generator function uses theco_firstlineno andco_lnotabattributes of the code objectcode to find the offsets which are starts oflines in the source code. They are generated as(offset,lineno) pairs.
Detect all offsets in the code objectcode which are jump targets, andreturn a list of these offsets.
Sequence of operation names, indexable using the bytecode.
Dictionary mapping operation names to bytecodes.
Sequence of all compare operation names.
Sequence of bytecodes that have a constant parameter.
Sequence of bytecodes that access a free variable.
Sequence of bytecodes that access an attribute by name.
Sequence of bytecodes that have a relative jump target.
Sequence of bytecodes that have an absolute jump target.
Sequence of bytecodes that access a local variable.
Sequence of bytecodes of Boolean operations.
The Python compiler currently generates the following bytecode instructions.
General instructions
Do nothing code. Used as a placeholder by the bytecode optimizer.
Removes the top-of-stack (TOS) item.
Swaps the two top-most stack items.
Lifts second and third stack item one position up, moves top down to positionthree.
Duplicates the reference on top of the stack.
Duplicates the two references on top of the stack, leaving them in thesame order.
Unary operations
Unary operations take the top of the stack, apply the operation, and push theresult back on the stack.
ImplementsTOS=+TOS.
ImplementsTOS=-TOS.
ImplementsTOS=notTOS.
ImplementsTOS=~TOS.
ImplementsTOS=iter(TOS).
Binary operations
Binary operations remove the top of the stack (TOS) and the second top-moststack item (TOS1) from the stack. They perform the operation, and put theresult back on the stack.
ImplementsTOS=TOS1**TOS.
ImplementsTOS=TOS1*TOS.
ImplementsTOS=TOS1//TOS.
ImplementsTOS=TOS1/TOS.
ImplementsTOS=TOS1%TOS.
ImplementsTOS=TOS1+TOS.
ImplementsTOS=TOS1-TOS.
ImplementsTOS=TOS1[TOS].
ImplementsTOS=TOS1<<TOS.
ImplementsTOS=TOS1>>TOS.
ImplementsTOS=TOS1&TOS.
ImplementsTOS=TOS1^TOS.
ImplementsTOS=TOS1|TOS.
In-place operations
In-place operations are like binary operations, in that they remove TOS andTOS1, and push the result back on the stack, but the operation is done in-placewhen TOS1 supports it, and the resulting TOS may be (but does not have to be)the original TOS1.
Implements in-placeTOS=TOS1**TOS.
Implements in-placeTOS=TOS1*TOS.
Implements in-placeTOS=TOS1//TOS.
Implements in-placeTOS=TOS1/TOS.
Implements in-placeTOS=TOS1%TOS.
Implements in-placeTOS=TOS1+TOS.
Implements in-placeTOS=TOS1-TOS.
Implements in-placeTOS=TOS1<<TOS.
Implements in-placeTOS=TOS1>>TOS.
Implements in-placeTOS=TOS1&TOS.
Implements in-placeTOS=TOS1^TOS.
Implements in-placeTOS=TOS1|TOS.
ImplementsTOS1[TOS]=TOS2.
ImplementsdelTOS1[TOS].
Miscellaneous opcodes
Implements the expression statement for the interactive mode. TOS is removedfrom the stack and printed. In non-interactive mode, an expression statement isterminated withPOP_STACK.
Continues a loop due to acontinue statement.target is theaddress to jump to (which should be aFOR_ITER instruction).
Callsset.add(TOS1[-i],TOS). Used to implement set comprehensions.
Callslist.append(TOS[-i],TOS). Used to implement list comprehensions.
Callsdict.setitem(TOS1[-i],TOS,TOS1). Used to implement dictcomprehensions.
For all of the SET_ADD, LIST_APPEND and MAP_ADD instructions, while theadded value or key/value pair is popped off, the container object remains onthe stack so that it is available for further iterations of the loop.
Returns with TOS to the caller of the function.
Loads all symbols not starting with'_' directly from the module TOS to thelocal namespace. The module is popped after loading all names. This opcodeimplementsfrommoduleimport*.
Removes one block from the block stack. Per frame, there is a stack of blocks,denoting nested loops, try statements, and such.
Removes one block from the block stack. The popped block must be an exceptionhandler block, as implicitly created when entering an except handler.In addition to popping extraneous values from the frame stack, thelast three popped values are used to restore the exception state.
Terminates afinally clause. The interpreter recalls whether theexception has to be re-raised, or whether the function returns, and continueswith the outer-next block.
Pushesbuiltins.__build_class__() onto the stack. It is later calledbyCALL_FUNCTION to construct a class.
This opcode performs several operations before a with block starts. First,it loads__exit__() from the context manager and pushes it ontothe stack for later use byWITH_CLEANUP. Then,__enter__() is called, and a finally block pointing todeltais pushed. Finally, the result of calling the enter method is pushed ontothe stack. The next opcode will either ignore it (POP_TOP), orstore it in (a) variable(s) (STORE_FAST,STORE_NAME, orUNPACK_SEQUENCE).
Cleans up the stack when awith statement block exits. TOS isthe context manager’s__exit__() bound method. Below TOS are 1–3values indicating how/why the finally clause was entered:
In the last case,TOS(SECOND,THIRD,FOURTH) is called, otherwiseTOS(None,None,None). In addition, TOS is removed from the stack.
If the stack represents an exception,and the function call returnsa ‘true’ value, this information is “zapped” and replaced with a singleWHY_SILENCED to preventEND_FINALLY from re-raising the exception.(But non-local gotos will still be resumed.)
Pops TOS from the stack and stores it as the current frame’sf_locals.This is used in class construction.
All of the following opcodes expect arguments. An argument is two bytes, withthe more significant byte last.
Implementsname=TOS.namei is the index ofname in the attributeco_names of the code object. The compiler tries to useSTORE_FASTorSTORE_GLOBAL if possible.
Implementsdelname, wherenamei is the index intoco_namesattribute of the code object.
Unpacks TOS intocount individual values, which are put onto the stackright-to-left.
Implements assignment with a starred target: Unpacks an iterable in TOS intoindividual values, where the total number of values can be smaller than thenumber of items in the iterable: one the new values will be a list of allleftover items.
The low byte ofcounts is the number of values before the list value, thehigh byte ofcounts the number of values after it. The resulting valuesare put onto the stack right-to-left.
ImplementsTOS.name=TOS1, wherenamei is the index of name inco_names.
ImplementsdelTOS.name, usingnamei as index intoco_names.
Works asSTORE_NAME, but stores the name as a global.
Works asDELETE_NAME, but deletes a global name.
Pushesco_consts[consti] onto the stack.
Pushes the value associated withco_names[namei] onto the stack.
Creates a tuple consumingcount items from the stack, and pushes the resultingtuple onto the stack.
Works asBUILD_TUPLE, but creates a list.
Works asBUILD_TUPLE, but creates a set.
Pushes a new dictionary object onto the stack. The dictionary is pre-sizedto holdcount entries.
Replaces TOS withgetattr(TOS,co_names[namei]).
Performs a Boolean operation. The operation name can be found incmp_op[opname].
Imports the moduleco_names[namei]. TOS and TOS1 are popped and providethefromlist andlevel arguments of__import__(). The moduleobject is pushed onto the stack. The current namespace is not affected:for a proper import statement, a subsequentSTORE_FAST instructionmodifies the namespace.
Loads the attributeco_names[namei] from the module found in TOS. Theresulting object is pushed onto the stack, to be subsequently stored by aSTORE_FAST instruction.
Increments bytecode counter bydelta.
If TOS is true, sets the bytecode counter totarget. TOS is popped.
If TOS is false, sets the bytecode counter totarget. TOS is popped.
If TOS is true, sets the bytecode counter totarget and leaves TOSon the stack. Otherwise (TOS is false), TOS is popped.
If TOS is false, sets the bytecode counter totarget and leavesTOS on the stack. Otherwise (TOS is true), TOS is popped.
Set bytecode counter totarget.
TOS is aniterator. Call its__next__() method.If this yields a new value, push it on the stack (leaving the iterator belowit). If the iterator indicates it is exhaustedTOS is popped, and thebyte code counter is incremented bydelta.
Loads the global namedco_names[namei] onto the stack.
Pushes a block for a loop onto the block stack. The block spans from thecurrent instruction with a size ofdelta bytes.
Pushes a try block from a try-except clause onto the block stack.delta pointsto the first except block.
Pushes a try block from a try-except clause onto the block stack.delta pointsto the finally block.
Store a key and value pair in a dictionary. Pops the key and value while leavingthe dictionary on the stack.
Pushes a reference to the localco_varnames[var_num] onto the stack.
Stores TOS into the localco_varnames[var_num].
Deletes localco_varnames[var_num].
Pushes a reference to the cell contained in sloti of the cell and freevariable storage. The name of the variable isco_cellvars[i] ifi isless than the length ofco_cellvars. Otherwise it isco_freevars[i-len(co_cellvars)].
Loads the cell contained in sloti of the cell and free variable storage.Pushes a reference to the object the cell contains on the stack.
Stores TOS into the cell contained in sloti of the cell and free variablestorage.
Empties the cell contained in sloti of the cell and free variable storage.Used by thedel statement.
Raises an exception.argc indicates the number of parameters to the raisestatement, ranging from 0 to 3. The handler will find the traceback as TOS2,the parameter as TOS1, and the exception as TOS.
Calls a function. The low byte ofargc indicates the number of positionalparameters, the high byte the number of keyword parameters. On the stack, theopcode finds the keyword parameters first. For each keyword argument, the valueis on top of the key. Below the keyword parameters, the positional parametersare on the stack, with the right-most parameter on top. Below the parameters,the function object to call is on the stack. Pops all function arguments, andthe function itself off the stack, and pushes the return value.
Pushes a new function object on the stack. From bottom to top, the consumedstack must consist of
Creates a new function object, sets its__closure__ slot, and pushes it onthe stack. TOS is thequalified name of the function, TOS1 is thecode associated with the function, and TOS2 is the tuple containing cells forthe closure’s free variables. The function also hasargc default parameters,which are found below the cells.
Pushes a slice object on the stack.argc must be 2 or 3. If it is 2,slice(TOS1,TOS) is pushed; if it is 3,slice(TOS2,TOS1,TOS) ispushed. See theslice() built-in function for more information.
Prefixes any opcode which has an argument too big to fit into the default twobytes.ext holds two additional bytes which, taken together with thesubsequent opcode’s argument, comprise a four-byte argument,ext being the twomost-significant bytes.
Calls a function.argc is interpreted as inCALL_FUNCTION. The top elementon the stack contains the variable argument list, followed by keyword andpositional arguments.
Calls a function.argc is interpreted as inCALL_FUNCTION. The top elementon the stack contains the keyword arguments dictionary, followed by explicitkeyword and positional arguments.
Calls a function.argc is interpreted as inCALL_FUNCTION. The topelement on the stack contains the keyword arguments dictionary, followed by thevariable-arguments tuple, followed by explicit keyword and positional arguments.
This is not really an opcode. It identifies the dividing line between opcodeswhich don’t take arguments<HAVE_ARGUMENT and those which do>=HAVE_ARGUMENT.
31.11.compileall — Byte-compile Python libraries
31.13.pickletools — Tools for pickle developers
Enter search terms or a module, class or function name.