1:mod:`dis` --- Disassembler for Python bytecode 2=============================================== 3 4.. module:: dis 5 :synopsis: Disassembler for Python bytecode. 6 7**Source code:** :source:`Lib/dis.py` 8 9-------------- 10 11The :mod:`dis` module supports the analysis of CPython :term:`bytecode` by 12disassembling it. The CPython bytecode which this module takes as an input is 13defined in the file :file:`Include/opcode.h` and used by the compiler and the 14interpreter. 15 16.. impl-detail:: 17 18 Bytecode is an implementation detail of the CPython interpreter. No 19 guarantees are made that bytecode will not be added, removed, or changed 20 between versions of Python. Use of this module should not be considered to 21 work across Python VMs or Python releases. 22 23 .. versionchanged:: 3.6 24 Use 2 bytes for each instruction. Previously the number of bytes varied 25 by instruction. 26 27 28Example: Given the function :func:`myfunc`:: 29 30 def myfunc(alist): 31 return len(alist) 32 33the following command can be used to display the disassembly of 34:func:`myfunc`:: 35 36 >>> dis.dis(myfunc) 37 2 0 LOAD_GLOBAL 0 (len) 38 2 LOAD_FAST 0 (alist) 39 4 CALL_FUNCTION 1 40 6 RETURN_VALUE 41 42(The "2" is a line number). 43 44Bytecode analysis 45----------------- 46 47.. versionadded:: 3.4 48 49The bytecode analysis API allows pieces of Python code to be wrapped in a 50:class:`Bytecode` object that provides easy access to details of the compiled 51code. 52 53.. class:: Bytecode(x, *, first_line=None, current_offset=None) 54 55 56 Analyse the bytecode corresponding to a function, generator, asynchronous 57 generator, coroutine, method, string of source code, or a code object (as 58 returned by :func:`compile`). 59 60 This is a convenience wrapper around many of the functions listed below, most 61 notably :func:`get_instructions`, as iterating over a :class:`Bytecode` 62 instance yields the bytecode operations as :class:`Instruction` instances. 63 64 If *first_line* is not ``None``, it indicates the line number that should be 65 reported for the first source line in the disassembled code. Otherwise, the 66 source line information (if any) is taken directly from the disassembled code 67 object. 68 69 If *current_offset* is not ``None``, it refers to an instruction offset in the 70 disassembled code. Setting this means :meth:`.dis` will display a "current 71 instruction" marker against the specified opcode. 72 73 .. classmethod:: from_traceback(tb) 74 75 Construct a :class:`Bytecode` instance from the given traceback, setting 76 *current_offset* to the instruction responsible for the exception. 77 78 .. data:: codeobj 79 80 The compiled code object. 81 82 .. data:: first_line 83 84 The first source line of the code object (if available) 85 86 .. method:: dis() 87 88 Return a formatted view of the bytecode operations (the same as printed by 89 :func:`dis.dis`, but returned as a multi-line string). 90 91 .. method:: info() 92 93 Return a formatted multi-line string with detailed information about the 94 code object, like :func:`code_info`. 95 96 .. versionchanged:: 3.7 97 This can now handle coroutine and asynchronous generator objects. 98 99Example:: 100 101 >>> bytecode = dis.Bytecode(myfunc) 102 >>> for instr in bytecode: 103 ... print(instr.opname) 104 ... 105 LOAD_GLOBAL 106 LOAD_FAST 107 CALL_FUNCTION 108 RETURN_VALUE 109 110 111Analysis functions 112------------------ 113 114The :mod:`dis` module also defines the following analysis functions that convert 115the input directly to the desired output. They can be useful if only a single 116operation is being performed, so the intermediate analysis object isn't useful: 117 118.. function:: code_info(x) 119 120 Return a formatted multi-line string with detailed code object information 121 for the supplied function, generator, asynchronous generator, coroutine, 122 method, source code string or code object. 123 124 Note that the exact contents of code info strings are highly implementation 125 dependent and they may change arbitrarily across Python VMs or Python 126 releases. 127 128 .. versionadded:: 3.2 129 130 .. versionchanged:: 3.7 131 This can now handle coroutine and asynchronous generator objects. 132 133 134.. function:: show_code(x, *, file=None) 135 136 Print detailed code object information for the supplied function, method, 137 source code string or code object to *file* (or ``sys.stdout`` if *file* 138 is not specified). 139 140 This is a convenient shorthand for ``print(code_info(x), file=file)``, 141 intended for interactive exploration at the interpreter prompt. 142 143 .. versionadded:: 3.2 144 145 .. versionchanged:: 3.4 146 Added *file* parameter. 147 148 149.. function:: dis(x=None, *, file=None, depth=None) 150 151 Disassemble the *x* object. *x* can denote either a module, a class, a 152 method, a function, a generator, an asynchronous generator, a coroutine, 153 a code object, a string of source code or a byte sequence of raw bytecode. 154 For a module, it disassembles all functions. For a class, it disassembles 155 all methods (including class and static methods). For a code object or 156 sequence of raw bytecode, it prints one line per bytecode instruction. 157 It also recursively disassembles nested code objects (the code of 158 comprehensions, generator expressions and nested functions, and the code 159 used for building nested classes). 160 Strings are first compiled to code objects with the :func:`compile` 161 built-in function before being disassembled. If no object is provided, this 162 function disassembles the last traceback. 163 164 The disassembly is written as text to the supplied *file* argument if 165 provided and to ``sys.stdout`` otherwise. 166 167 The maximal depth of recursion is limited by *depth* unless it is ``None``. 168 ``depth=0`` means no recursion. 169 170 .. versionchanged:: 3.4 171 Added *file* parameter. 172 173 .. versionchanged:: 3.7 174 Implemented recursive disassembling and added *depth* parameter. 175 176 .. versionchanged:: 3.7 177 This can now handle coroutine and asynchronous generator objects. 178 179 180.. function:: distb(tb=None, *, file=None) 181 182 Disassemble the top-of-stack function of a traceback, using the last 183 traceback if none was passed. The instruction causing the exception is 184 indicated. 185 186 The disassembly is written as text to the supplied *file* argument if 187 provided and to ``sys.stdout`` otherwise. 188 189 .. versionchanged:: 3.4 190 Added *file* parameter. 191 192 193.. function:: disassemble(code, lasti=-1, *, file=None) 194 disco(code, lasti=-1, *, file=None) 195 196 Disassemble a code object, indicating the last instruction if *lasti* was 197 provided. The output is divided in the following columns: 198 199 #. the line number, for the first instruction of each line 200 #. the current instruction, indicated as ``-->``, 201 #. a labelled instruction, indicated with ``>>``, 202 #. the address of the instruction, 203 #. the operation code name, 204 #. operation parameters, and 205 #. interpretation of the parameters in parentheses. 206 207 The parameter interpretation recognizes local and global variable names, 208 constant values, branch targets, and compare operators. 209 210 The disassembly is written as text to the supplied *file* argument if 211 provided and to ``sys.stdout`` otherwise. 212 213 .. versionchanged:: 3.4 214 Added *file* parameter. 215 216 217.. function:: get_instructions(x, *, first_line=None) 218 219 Return an iterator over the instructions in the supplied function, method, 220 source code string or code object. 221 222 The iterator generates a series of :class:`Instruction` named tuples giving 223 the details of each operation in the supplied code. 224 225 If *first_line* is not ``None``, it indicates the line number that should be 226 reported for the first source line in the disassembled code. Otherwise, the 227 source line information (if any) is taken directly from the disassembled code 228 object. 229 230 .. versionadded:: 3.4 231 232 233.. function:: findlinestarts(code) 234 235 This generator function uses the ``co_firstlineno`` and ``co_lnotab`` 236 attributes of the code object *code* to find the offsets which are starts of 237 lines in the source code. They are generated as ``(offset, lineno)`` pairs. 238 See :source:`Objects/lnotab_notes.txt` for the ``co_lnotab`` format and 239 how to decode it. 240 241 .. versionchanged:: 3.6 242 Line numbers can be decreasing. Before, they were always increasing. 243 244 245.. function:: findlabels(code) 246 247 Detect all offsets in the raw compiled bytecode string *code* which are jump targets, and 248 return a list of these offsets. 249 250 251.. function:: stack_effect(opcode, oparg=None, *, jump=None) 252 253 Compute the stack effect of *opcode* with argument *oparg*. 254 255 If the code has a jump target and *jump* is ``True``, :func:`~stack_effect` 256 will return the stack effect of jumping. If *jump* is ``False``, 257 it will return the stack effect of not jumping. And if *jump* is 258 ``None`` (default), it will return the maximal stack effect of both cases. 259 260 .. versionadded:: 3.4 261 262 .. versionchanged:: 3.8 263 Added *jump* parameter. 264 265 266.. _bytecodes: 267 268Python Bytecode Instructions 269---------------------------- 270 271The :func:`get_instructions` function and :class:`Bytecode` class provide 272details of bytecode instructions as :class:`Instruction` instances: 273 274.. class:: Instruction 275 276 Details for a bytecode operation 277 278 .. data:: opcode 279 280 numeric code for operation, corresponding to the opcode values listed 281 below and the bytecode values in the :ref:`opcode_collections`. 282 283 284 .. data:: opname 285 286 human readable name for operation 287 288 289 .. data:: arg 290 291 numeric argument to operation (if any), otherwise ``None`` 292 293 294 .. data:: argval 295 296 resolved arg value (if known), otherwise same as arg 297 298 299 .. data:: argrepr 300 301 human readable description of operation argument 302 303 304 .. data:: offset 305 306 start index of operation within bytecode sequence 307 308 309 .. data:: starts_line 310 311 line started by this opcode (if any), otherwise ``None`` 312 313 314 .. data:: is_jump_target 315 316 ``True`` if other code jumps to here, otherwise ``False`` 317 318 .. versionadded:: 3.4 319 320 321The Python compiler currently generates the following bytecode instructions. 322 323 324**General instructions** 325 326.. opcode:: NOP 327 328 Do nothing code. Used as a placeholder by the bytecode optimizer. 329 330 331.. opcode:: POP_TOP 332 333 Removes the top-of-stack (TOS) item. 334 335 336.. opcode:: ROT_TWO 337 338 Swaps the two top-most stack items. 339 340 341.. opcode:: ROT_THREE 342 343 Lifts second and third stack item one position up, moves top down to position 344 three. 345 346 347.. opcode:: ROT_FOUR 348 349 Lifts second, third and fourth stack items one position up, moves top down 350 to position four. 351 352 .. versionadded:: 3.8 353 354 355.. opcode:: DUP_TOP 356 357 Duplicates the reference on top of the stack. 358 359 .. versionadded:: 3.2 360 361 362.. opcode:: DUP_TOP_TWO 363 364 Duplicates the two references on top of the stack, leaving them in the 365 same order. 366 367 .. versionadded:: 3.2 368 369 370**Unary operations** 371 372Unary operations take the top of the stack, apply the operation, and push the 373result back on the stack. 374 375.. opcode:: UNARY_POSITIVE 376 377 Implements ``TOS = +TOS``. 378 379 380.. opcode:: UNARY_NEGATIVE 381 382 Implements ``TOS = -TOS``. 383 384 385.. opcode:: UNARY_NOT 386 387 Implements ``TOS = not TOS``. 388 389 390.. opcode:: UNARY_INVERT 391 392 Implements ``TOS = ~TOS``. 393 394 395.. opcode:: GET_ITER 396 397 Implements ``TOS = iter(TOS)``. 398 399 400.. opcode:: GET_YIELD_FROM_ITER 401 402 If ``TOS`` is a :term:`generator iterator` or :term:`coroutine` object 403 it is left as is. Otherwise, implements ``TOS = iter(TOS)``. 404 405 .. versionadded:: 3.5 406 407 408**Binary operations** 409 410Binary operations remove the top of the stack (TOS) and the second top-most 411stack item (TOS1) from the stack. They perform the operation, and put the 412result back on the stack. 413 414.. opcode:: BINARY_POWER 415 416 Implements ``TOS = TOS1 ** TOS``. 417 418 419.. opcode:: BINARY_MULTIPLY 420 421 Implements ``TOS = TOS1 * TOS``. 422 423 424.. opcode:: BINARY_MATRIX_MULTIPLY 425 426 Implements ``TOS = TOS1 @ TOS``. 427 428 .. versionadded:: 3.5 429 430 431.. opcode:: BINARY_FLOOR_DIVIDE 432 433 Implements ``TOS = TOS1 // TOS``. 434 435 436.. opcode:: BINARY_TRUE_DIVIDE 437 438 Implements ``TOS = TOS1 / TOS``. 439 440 441.. opcode:: BINARY_MODULO 442 443 Implements ``TOS = TOS1 % TOS``. 444 445 446.. opcode:: BINARY_ADD 447 448 Implements ``TOS = TOS1 + TOS``. 449 450 451.. opcode:: BINARY_SUBTRACT 452 453 Implements ``TOS = TOS1 - TOS``. 454 455 456.. opcode:: BINARY_SUBSCR 457 458 Implements ``TOS = TOS1[TOS]``. 459 460 461.. opcode:: BINARY_LSHIFT 462 463 Implements ``TOS = TOS1 << TOS``. 464 465 466.. opcode:: BINARY_RSHIFT 467 468 Implements ``TOS = TOS1 >> TOS``. 469 470 471.. opcode:: BINARY_AND 472 473 Implements ``TOS = TOS1 & TOS``. 474 475 476.. opcode:: BINARY_XOR 477 478 Implements ``TOS = TOS1 ^ TOS``. 479 480 481.. opcode:: BINARY_OR 482 483 Implements ``TOS = TOS1 | TOS``. 484 485 486**In-place operations** 487 488In-place operations are like binary operations, in that they remove TOS and 489TOS1, and push the result back on the stack, but the operation is done in-place 490when TOS1 supports it, and the resulting TOS may be (but does not have to be) 491the original TOS1. 492 493.. opcode:: INPLACE_POWER 494 495 Implements in-place ``TOS = TOS1 ** TOS``. 496 497 498.. opcode:: INPLACE_MULTIPLY 499 500 Implements in-place ``TOS = TOS1 * TOS``. 501 502 503.. opcode:: INPLACE_MATRIX_MULTIPLY 504 505 Implements in-place ``TOS = TOS1 @ TOS``. 506 507 .. versionadded:: 3.5 508 509 510.. opcode:: INPLACE_FLOOR_DIVIDE 511 512 Implements in-place ``TOS = TOS1 // TOS``. 513 514 515.. opcode:: INPLACE_TRUE_DIVIDE 516 517 Implements in-place ``TOS = TOS1 / TOS``. 518 519 520.. opcode:: INPLACE_MODULO 521 522 Implements in-place ``TOS = TOS1 % TOS``. 523 524 525.. opcode:: INPLACE_ADD 526 527 Implements in-place ``TOS = TOS1 + TOS``. 528 529 530.. opcode:: INPLACE_SUBTRACT 531 532 Implements in-place ``TOS = TOS1 - TOS``. 533 534 535.. opcode:: INPLACE_LSHIFT 536 537 Implements in-place ``TOS = TOS1 << TOS``. 538 539 540.. opcode:: INPLACE_RSHIFT 541 542 Implements in-place ``TOS = TOS1 >> TOS``. 543 544 545.. opcode:: INPLACE_AND 546 547 Implements in-place ``TOS = TOS1 & TOS``. 548 549 550.. opcode:: INPLACE_XOR 551 552 Implements in-place ``TOS = TOS1 ^ TOS``. 553 554 555.. opcode:: INPLACE_OR 556 557 Implements in-place ``TOS = TOS1 | TOS``. 558 559 560.. opcode:: STORE_SUBSCR 561 562 Implements ``TOS1[TOS] = TOS2``. 563 564 565.. opcode:: DELETE_SUBSCR 566 567 Implements ``del TOS1[TOS]``. 568 569 570**Coroutine opcodes** 571 572.. opcode:: GET_AWAITABLE 573 574 Implements ``TOS = get_awaitable(TOS)``, where ``get_awaitable(o)`` 575 returns ``o`` if ``o`` is a coroutine object or a generator object with 576 the CO_ITERABLE_COROUTINE flag, or resolves 577 ``o.__await__``. 578 579 .. versionadded:: 3.5 580 581 582.. opcode:: GET_AITER 583 584 Implements ``TOS = TOS.__aiter__()``. 585 586 .. versionadded:: 3.5 587 .. versionchanged:: 3.7 588 Returning awaitable objects from ``__aiter__`` is no longer 589 supported. 590 591 592.. opcode:: GET_ANEXT 593 594 Implements ``PUSH(get_awaitable(TOS.__anext__()))``. See ``GET_AWAITABLE`` 595 for details about ``get_awaitable`` 596 597 .. versionadded:: 3.5 598 599 600.. opcode:: END_ASYNC_FOR 601 602 Terminates an :keyword:`async for` loop. Handles an exception raised 603 when awaiting a next item. If TOS is :exc:`StopAsyncIteration` pop 7 604 values from the stack and restore the exception state using the second 605 three of them. Otherwise re-raise the exception using the three values 606 from the stack. An exception handler block is removed from the block stack. 607 608 .. versionadded:: 3.8 609 610 611.. opcode:: BEFORE_ASYNC_WITH 612 613 Resolves ``__aenter__`` and ``__aexit__`` from the object on top of the 614 stack. Pushes ``__aexit__`` and result of ``__aenter__()`` to the stack. 615 616 .. versionadded:: 3.5 617 618 619.. opcode:: SETUP_ASYNC_WITH 620 621 Creates a new frame object. 622 623 .. versionadded:: 3.5 624 625 626 627**Miscellaneous opcodes** 628 629.. opcode:: PRINT_EXPR 630 631 Implements the expression statement for the interactive mode. TOS is removed 632 from the stack and printed. In non-interactive mode, an expression statement 633 is terminated with :opcode:`POP_TOP`. 634 635 636.. opcode:: SET_ADD (i) 637 638 Calls ``set.add(TOS1[-i], TOS)``. Used to implement set comprehensions. 639 640 641.. opcode:: LIST_APPEND (i) 642 643 Calls ``list.append(TOS1[-i], TOS)``. Used to implement list comprehensions. 644 645 646.. opcode:: MAP_ADD (i) 647 648 Calls ``dict.__setitem__(TOS1[-i], TOS1, TOS)``. Used to implement dict 649 comprehensions. 650 651 .. versionadded:: 3.1 652 .. versionchanged:: 3.8 653 Map value is TOS and map key is TOS1. Before, those were reversed. 654 655For all of the :opcode:`SET_ADD`, :opcode:`LIST_APPEND` and :opcode:`MAP_ADD` 656instructions, while the added value or key/value pair is popped off, the 657container object remains on the stack so that it is available for further 658iterations of the loop. 659 660 661.. opcode:: RETURN_VALUE 662 663 Returns with TOS to the caller of the function. 664 665 666.. opcode:: YIELD_VALUE 667 668 Pops TOS and yields it from a :term:`generator`. 669 670 671.. opcode:: YIELD_FROM 672 673 Pops TOS and delegates to it as a subiterator from a :term:`generator`. 674 675 .. versionadded:: 3.3 676 677 678.. opcode:: SETUP_ANNOTATIONS 679 680 Checks whether ``__annotations__`` is defined in ``locals()``, if not it is 681 set up to an empty ``dict``. This opcode is only emitted if a class 682 or module body contains :term:`variable annotations <variable annotation>` 683 statically. 684 685 .. versionadded:: 3.6 686 687 688.. opcode:: IMPORT_STAR 689 690 Loads all symbols not starting with ``'_'`` directly from the module TOS to 691 the local namespace. The module is popped after loading all names. This 692 opcode implements ``from module import *``. 693 694 695.. opcode:: POP_BLOCK 696 697 Removes one block from the block stack. Per frame, there is a stack of 698 blocks, denoting :keyword:`try` statements, and such. 699 700 701.. opcode:: POP_EXCEPT 702 703 Removes one block from the block stack. The popped block must be an exception 704 handler block, as implicitly created when entering an except handler. In 705 addition to popping extraneous values from the frame stack, the last three 706 popped values are used to restore the exception state. 707 708 709.. opcode:: RERAISE 710 711 Re-raises the exception currently on top of the stack. If oparg is non-zero, 712 restores ``f_lasti`` of the current frame to its value when the exception was raised. 713 714 .. versionadded:: 3.9 715 716 717.. opcode:: WITH_EXCEPT_START 718 719 Calls the function in position 7 on the stack with the top three 720 items on the stack as arguments. 721 Used to implement the call ``context_manager.__exit__(*exc_info())`` when an exception 722 has occurred in a :keyword:`with` statement. 723 724 .. versionadded:: 3.9 725 726 727.. opcode:: LOAD_ASSERTION_ERROR 728 729 Pushes :exc:`AssertionError` onto the stack. Used by the :keyword:`assert` 730 statement. 731 732 .. versionadded:: 3.9 733 734 735.. opcode:: LOAD_BUILD_CLASS 736 737 Pushes :func:`builtins.__build_class__` onto the stack. It is later called 738 by :opcode:`CALL_FUNCTION` to construct a class. 739 740 741.. opcode:: SETUP_WITH (delta) 742 743 This opcode performs several operations before a with block starts. First, 744 it loads :meth:`~object.__exit__` from the context manager and pushes it onto 745 the stack for later use by :opcode:`WITH_EXCEPT_START`. Then, 746 :meth:`~object.__enter__` is called, and a finally block pointing to *delta* 747 is pushed. Finally, the result of calling the ``__enter__()`` method is pushed onto 748 the stack. The next opcode will either ignore it (:opcode:`POP_TOP`), or 749 store it in (a) variable(s) (:opcode:`STORE_FAST`, :opcode:`STORE_NAME`, or 750 :opcode:`UNPACK_SEQUENCE`). 751 752 .. versionadded:: 3.2 753 754 755.. opcode:: COPY_DICT_WITHOUT_KEYS 756 757 TOS is a tuple of mapping keys, and TOS1 is the match subject. Replace TOS 758 with a :class:`dict` formed from the items of TOS1, but without any of the 759 keys in TOS. 760 761 .. versionadded:: 3.10 762 763 764.. opcode:: GET_LEN 765 766 Push ``len(TOS)`` onto the stack. 767 768 .. versionadded:: 3.10 769 770 771.. opcode:: MATCH_MAPPING 772 773 If TOS is an instance of :class:`collections.abc.Mapping` (or, more technically: if 774 it has the :const:`Py_TPFLAGS_MAPPING` flag set in its 775 :c:member:`~PyTypeObject.tp_flags`), push ``True`` onto the stack. Otherwise, push 776 ``False``. 777 778 .. versionadded:: 3.10 779 780 781.. opcode:: MATCH_SEQUENCE 782 783 If TOS is an instance of :class:`collections.abc.Sequence` and is *not* an instance 784 of :class:`str`/:class:`bytes`/:class:`bytearray` (or, more technically: if it has 785 the :const:`Py_TPFLAGS_SEQUENCE` flag set in its :c:member:`~PyTypeObject.tp_flags`), 786 push ``True`` onto the stack. Otherwise, push ``False``. 787 788 .. versionadded:: 3.10 789 790 791.. opcode:: MATCH_KEYS 792 793 TOS is a tuple of mapping keys, and TOS1 is the match subject. If TOS1 794 contains all of the keys in TOS, push a :class:`tuple` containing the 795 corresponding values, followed by ``True``. Otherwise, push ``None``, 796 followed by ``False``. 797 798 .. versionadded:: 3.10 799 800 801All of the following opcodes use their arguments. 802 803.. opcode:: STORE_NAME (namei) 804 805 Implements ``name = TOS``. *namei* is the index of *name* in the attribute 806 :attr:`co_names` of the code object. The compiler tries to use 807 :opcode:`STORE_FAST` or :opcode:`STORE_GLOBAL` if possible. 808 809 810.. opcode:: DELETE_NAME (namei) 811 812 Implements ``del name``, where *namei* is the index into :attr:`co_names` 813 attribute of the code object. 814 815 816.. opcode:: UNPACK_SEQUENCE (count) 817 818 Unpacks TOS into *count* individual values, which are put onto the stack 819 right-to-left. 820 821 822.. opcode:: UNPACK_EX (counts) 823 824 Implements assignment with a starred target: Unpacks an iterable in TOS into 825 individual values, where the total number of values can be smaller than the 826 number of items in the iterable: one of the new values will be a list of all 827 leftover items. 828 829 The low byte of *counts* is the number of values before the list value, the 830 high byte of *counts* the number of values after it. The resulting values 831 are put onto the stack right-to-left. 832 833 834.. opcode:: STORE_ATTR (namei) 835 836 Implements ``TOS.name = TOS1``, where *namei* is the index of name in 837 :attr:`co_names`. 838 839 840.. opcode:: DELETE_ATTR (namei) 841 842 Implements ``del TOS.name``, using *namei* as index into :attr:`co_names`. 843 844 845.. opcode:: STORE_GLOBAL (namei) 846 847 Works as :opcode:`STORE_NAME`, but stores the name as a global. 848 849 850.. opcode:: DELETE_GLOBAL (namei) 851 852 Works as :opcode:`DELETE_NAME`, but deletes a global name. 853 854 855.. opcode:: LOAD_CONST (consti) 856 857 Pushes ``co_consts[consti]`` onto the stack. 858 859 860.. opcode:: LOAD_NAME (namei) 861 862 Pushes the value associated with ``co_names[namei]`` onto the stack. 863 864 865.. opcode:: BUILD_TUPLE (count) 866 867 Creates a tuple consuming *count* items from the stack, and pushes the 868 resulting tuple onto the stack. 869 870 871.. opcode:: BUILD_LIST (count) 872 873 Works as :opcode:`BUILD_TUPLE`, but creates a list. 874 875 876.. opcode:: BUILD_SET (count) 877 878 Works as :opcode:`BUILD_TUPLE`, but creates a set. 879 880 881.. opcode:: BUILD_MAP (count) 882 883 Pushes a new dictionary object onto the stack. Pops ``2 * count`` items 884 so that the dictionary holds *count* entries: 885 ``{..., TOS3: TOS2, TOS1: TOS}``. 886 887 .. versionchanged:: 3.5 888 The dictionary is created from stack items instead of creating an 889 empty dictionary pre-sized to hold *count* items. 890 891 892.. opcode:: BUILD_CONST_KEY_MAP (count) 893 894 The version of :opcode:`BUILD_MAP` specialized for constant keys. Pops the 895 top element on the stack which contains a tuple of keys, then starting from 896 ``TOS1``, pops *count* values to form values in the built dictionary. 897 898 .. versionadded:: 3.6 899 900 901.. opcode:: BUILD_STRING (count) 902 903 Concatenates *count* strings from the stack and pushes the resulting string 904 onto the stack. 905 906 .. versionadded:: 3.6 907 908 909.. opcode:: LIST_TO_TUPLE 910 911 Pops a list from the stack and pushes a tuple containing the same values. 912 913 .. versionadded:: 3.9 914 915 916.. opcode:: LIST_EXTEND (i) 917 918 Calls ``list.extend(TOS1[-i], TOS)``. Used to build lists. 919 920 .. versionadded:: 3.9 921 922 923.. opcode:: SET_UPDATE (i) 924 925 Calls ``set.update(TOS1[-i], TOS)``. Used to build sets. 926 927 .. versionadded:: 3.9 928 929 930.. opcode:: DICT_UPDATE (i) 931 932 Calls ``dict.update(TOS1[-i], TOS)``. Used to build dicts. 933 934 .. versionadded:: 3.9 935 936 937.. opcode:: DICT_MERGE 938 939 Like :opcode:`DICT_UPDATE` but raises an exception for duplicate keys. 940 941 .. versionadded:: 3.9 942 943 944.. opcode:: LOAD_ATTR (namei) 945 946 Replaces TOS with ``getattr(TOS, co_names[namei])``. 947 948 949.. opcode:: COMPARE_OP (opname) 950 951 Performs a Boolean operation. The operation name can be found in 952 ``cmp_op[opname]``. 953 954 955.. opcode:: IS_OP (invert) 956 957 Performs ``is`` comparison, or ``is not`` if ``invert`` is 1. 958 959 .. versionadded:: 3.9 960 961 962.. opcode:: CONTAINS_OP (invert) 963 964 Performs ``in`` comparison, or ``not in`` if ``invert`` is 1. 965 966 .. versionadded:: 3.9 967 968 969.. opcode:: IMPORT_NAME (namei) 970 971 Imports the module ``co_names[namei]``. TOS and TOS1 are popped and provide 972 the *fromlist* and *level* arguments of :func:`__import__`. The module 973 object is pushed onto the stack. The current namespace is not affected: for 974 a proper import statement, a subsequent :opcode:`STORE_FAST` instruction 975 modifies the namespace. 976 977 978.. opcode:: IMPORT_FROM (namei) 979 980 Loads the attribute ``co_names[namei]`` from the module found in TOS. The 981 resulting object is pushed onto the stack, to be subsequently stored by a 982 :opcode:`STORE_FAST` instruction. 983 984 985.. opcode:: JUMP_FORWARD (delta) 986 987 Increments bytecode counter by *delta*. 988 989 990.. opcode:: POP_JUMP_IF_TRUE (target) 991 992 If TOS is true, sets the bytecode counter to *target*. TOS is popped. 993 994 .. versionadded:: 3.1 995 996 997.. opcode:: POP_JUMP_IF_FALSE (target) 998 999 If TOS is false, sets the bytecode counter to *target*. TOS is popped. 1000 1001 .. versionadded:: 3.1 1002 1003.. opcode:: JUMP_IF_NOT_EXC_MATCH (target) 1004 1005 Tests whether the second value on the stack is an exception matching TOS, 1006 and jumps if it is not. Pops two values from the stack. 1007 1008 .. versionadded:: 3.9 1009 1010 1011.. opcode:: JUMP_IF_TRUE_OR_POP (target) 1012 1013 If TOS is true, sets the bytecode counter to *target* and leaves TOS on the 1014 stack. Otherwise (TOS is false), TOS is popped. 1015 1016 .. versionadded:: 3.1 1017 1018 1019.. opcode:: JUMP_IF_FALSE_OR_POP (target) 1020 1021 If TOS is false, sets the bytecode counter to *target* and leaves TOS on the 1022 stack. Otherwise (TOS is true), TOS is popped. 1023 1024 .. versionadded:: 3.1 1025 1026 1027.. opcode:: JUMP_ABSOLUTE (target) 1028 1029 Set bytecode counter to *target*. 1030 1031 1032.. opcode:: FOR_ITER (delta) 1033 1034 TOS is an :term:`iterator`. Call its :meth:`~iterator.__next__` method. If 1035 this yields a new value, push it on the stack (leaving the iterator below 1036 it). If the iterator indicates it is exhausted, TOS is popped, and the byte 1037 code counter is incremented by *delta*. 1038 1039 1040.. opcode:: LOAD_GLOBAL (namei) 1041 1042 Loads the global named ``co_names[namei]`` onto the stack. 1043 1044 1045.. opcode:: SETUP_FINALLY (delta) 1046 1047 Pushes a try block from a try-finally or try-except clause onto the block 1048 stack. *delta* points to the finally block or the first except block. 1049 1050 1051.. opcode:: LOAD_FAST (var_num) 1052 1053 Pushes a reference to the local ``co_varnames[var_num]`` onto the stack. 1054 1055 1056.. opcode:: STORE_FAST (var_num) 1057 1058 Stores TOS into the local ``co_varnames[var_num]``. 1059 1060 1061.. opcode:: DELETE_FAST (var_num) 1062 1063 Deletes local ``co_varnames[var_num]``. 1064 1065 1066.. opcode:: LOAD_CLOSURE (i) 1067 1068 Pushes a reference to the cell contained in slot *i* of the cell and free 1069 variable storage. The name of the variable is ``co_cellvars[i]`` if *i* is 1070 less than the length of *co_cellvars*. Otherwise it is ``co_freevars[i - 1071 len(co_cellvars)]``. 1072 1073 1074.. opcode:: LOAD_DEREF (i) 1075 1076 Loads the cell contained in slot *i* of the cell and free variable storage. 1077 Pushes a reference to the object the cell contains on the stack. 1078 1079 1080.. opcode:: LOAD_CLASSDEREF (i) 1081 1082 Much like :opcode:`LOAD_DEREF` but first checks the locals dictionary before 1083 consulting the cell. This is used for loading free variables in class 1084 bodies. 1085 1086 .. versionadded:: 3.4 1087 1088 1089.. opcode:: STORE_DEREF (i) 1090 1091 Stores TOS into the cell contained in slot *i* of the cell and free variable 1092 storage. 1093 1094 1095.. opcode:: DELETE_DEREF (i) 1096 1097 Empties the cell contained in slot *i* of the cell and free variable storage. 1098 Used by the :keyword:`del` statement. 1099 1100 .. versionadded:: 3.2 1101 1102 1103.. opcode:: RAISE_VARARGS (argc) 1104 1105 Raises an exception using one of the 3 forms of the ``raise`` statement, 1106 depending on the value of *argc*: 1107 1108 * 0: ``raise`` (re-raise previous exception) 1109 * 1: ``raise TOS`` (raise exception instance or type at ``TOS``) 1110 * 2: ``raise TOS1 from TOS`` (raise exception instance or type at ``TOS1`` 1111 with ``__cause__`` set to ``TOS``) 1112 1113 1114.. opcode:: CALL_FUNCTION (argc) 1115 1116 Calls a callable object with positional arguments. 1117 *argc* indicates the number of positional arguments. 1118 The top of the stack contains positional arguments, with the right-most 1119 argument on top. Below the arguments is a callable object to call. 1120 ``CALL_FUNCTION`` pops all arguments and the callable object off the stack, 1121 calls the callable object with those arguments, and pushes the return value 1122 returned by the callable object. 1123 1124 .. versionchanged:: 3.6 1125 This opcode is used only for calls with positional arguments. 1126 1127 1128.. opcode:: CALL_FUNCTION_KW (argc) 1129 1130 Calls a callable object with positional (if any) and keyword arguments. 1131 *argc* indicates the total number of positional and keyword arguments. 1132 The top element on the stack contains a tuple with the names of the 1133 keyword arguments, which must be strings. 1134 Below that are the values for the keyword arguments, 1135 in the order corresponding to the tuple. 1136 Below that are positional arguments, with the right-most parameter on 1137 top. Below the arguments is a callable object to call. 1138 ``CALL_FUNCTION_KW`` pops all arguments and the callable object off the stack, 1139 calls the callable object with those arguments, and pushes the return value 1140 returned by the callable object. 1141 1142 .. versionchanged:: 3.6 1143 Keyword arguments are packed in a tuple instead of a dictionary, 1144 *argc* indicates the total number of arguments. 1145 1146 1147.. opcode:: CALL_FUNCTION_EX (flags) 1148 1149 Calls a callable object with variable set of positional and keyword 1150 arguments. If the lowest bit of *flags* is set, the top of the stack 1151 contains a mapping object containing additional keyword arguments. 1152 Before the callable is called, the mapping object and iterable object 1153 are each "unpacked" and their contents passed in as keyword and 1154 positional arguments respectively. 1155 ``CALL_FUNCTION_EX`` pops all arguments and the callable object off the stack, 1156 calls the callable object with those arguments, and pushes the return value 1157 returned by the callable object. 1158 1159 .. versionadded:: 3.6 1160 1161 1162.. opcode:: LOAD_METHOD (namei) 1163 1164 Loads a method named ``co_names[namei]`` from the TOS object. TOS is popped. 1165 This bytecode distinguishes two cases: if TOS has a method with the correct 1166 name, the bytecode pushes the unbound method and TOS. TOS will be used as 1167 the first argument (``self``) by :opcode:`CALL_METHOD` when calling the 1168 unbound method. Otherwise, ``NULL`` and the object return by the attribute 1169 lookup are pushed. 1170 1171 .. versionadded:: 3.7 1172 1173 1174.. opcode:: CALL_METHOD (argc) 1175 1176 Calls a method. *argc* is the number of positional arguments. 1177 Keyword arguments are not supported. This opcode is designed to be used 1178 with :opcode:`LOAD_METHOD`. Positional arguments are on top of the stack. 1179 Below them, the two items described in :opcode:`LOAD_METHOD` are on the 1180 stack (either ``self`` and an unbound method object or ``NULL`` and an 1181 arbitrary callable). All of them are popped and the return value is pushed. 1182 1183 .. versionadded:: 3.7 1184 1185 1186.. opcode:: MAKE_FUNCTION (flags) 1187 1188 Pushes a new function object on the stack. From bottom to top, the consumed 1189 stack must consist of values if the argument carries a specified flag value 1190 1191 * ``0x01`` a tuple of default values for positional-only and 1192 positional-or-keyword parameters in positional order 1193 * ``0x02`` a dictionary of keyword-only parameters' default values 1194 * ``0x04`` a tuple of strings containing parameters' annotations 1195 * ``0x08`` a tuple containing cells for free variables, making a closure 1196 * the code associated with the function (at TOS1) 1197 * the :term:`qualified name` of the function (at TOS) 1198 1199 .. versionchanged:: 3.10 1200 Flag value ``0x04`` is a tuple of strings instead of dictionary 1201 1202.. opcode:: BUILD_SLICE (argc) 1203 1204 .. index:: builtin: slice 1205 1206 Pushes a slice object on the stack. *argc* must be 2 or 3. If it is 2, 1207 ``slice(TOS1, TOS)`` is pushed; if it is 3, ``slice(TOS2, TOS1, TOS)`` is 1208 pushed. See the :func:`slice` built-in function for more information. 1209 1210 1211.. opcode:: EXTENDED_ARG (ext) 1212 1213 Prefixes any opcode which has an argument too big to fit into the default one 1214 byte. *ext* holds an additional byte which act as higher bits in the argument. 1215 For each opcode, at most three prefixal ``EXTENDED_ARG`` are allowed, forming 1216 an argument from two-byte to four-byte. 1217 1218 1219.. opcode:: FORMAT_VALUE (flags) 1220 1221 Used for implementing formatted literal strings (f-strings). Pops 1222 an optional *fmt_spec* from the stack, then a required *value*. 1223 *flags* is interpreted as follows: 1224 1225 * ``(flags & 0x03) == 0x00``: *value* is formatted as-is. 1226 * ``(flags & 0x03) == 0x01``: call :func:`str` on *value* before 1227 formatting it. 1228 * ``(flags & 0x03) == 0x02``: call :func:`repr` on *value* before 1229 formatting it. 1230 * ``(flags & 0x03) == 0x03``: call :func:`ascii` on *value* before 1231 formatting it. 1232 * ``(flags & 0x04) == 0x04``: pop *fmt_spec* from the stack and use 1233 it, else use an empty *fmt_spec*. 1234 1235 Formatting is performed using :c:func:`PyObject_Format`. The 1236 result is pushed on the stack. 1237 1238 .. versionadded:: 3.6 1239 1240 1241.. opcode:: MATCH_CLASS (count) 1242 1243 TOS is a tuple of keyword attribute names, TOS1 is the class being matched 1244 against, and TOS2 is the match subject. *count* is the number of positional 1245 sub-patterns. 1246 1247 Pop TOS. If TOS2 is an instance of TOS1 and has the positional and keyword 1248 attributes required by *count* and TOS, set TOS to ``True`` and TOS1 to a 1249 tuple of extracted attributes. Otherwise, set TOS to ``False``. 1250 1251 .. versionadded:: 3.10 1252 1253.. opcode:: GEN_START (kind) 1254 1255 Pops TOS. The ``kind`` operand corresponds to the type of generator or 1256 coroutine. The legal kinds are 0 for generator, 1 for coroutine, 1257 and 2 for async generator. 1258 1259 .. versionadded:: 3.10 1260 1261 1262.. opcode:: ROT_N (count) 1263 1264 Lift the top *count* stack items one position up, and move TOS down to 1265 position *count*. 1266 1267 .. versionadded:: 3.10 1268 1269 1270.. opcode:: HAVE_ARGUMENT 1271 1272 This is not really an opcode. It identifies the dividing line between 1273 opcodes which don't use their argument and those that do 1274 (``< HAVE_ARGUMENT`` and ``>= HAVE_ARGUMENT``, respectively). 1275 1276 .. versionchanged:: 3.6 1277 Now every instruction has an argument, but opcodes ``< HAVE_ARGUMENT`` 1278 ignore it. Before, only opcodes ``>= HAVE_ARGUMENT`` had an argument. 1279 1280 1281.. _opcode_collections: 1282 1283Opcode collections 1284------------------ 1285 1286These collections are provided for automatic introspection of bytecode 1287instructions: 1288 1289.. data:: opname 1290 1291 Sequence of operation names, indexable using the bytecode. 1292 1293 1294.. data:: opmap 1295 1296 Dictionary mapping operation names to bytecodes. 1297 1298 1299.. data:: cmp_op 1300 1301 Sequence of all compare operation names. 1302 1303 1304.. data:: hasconst 1305 1306 Sequence of bytecodes that access a constant. 1307 1308 1309.. data:: hasfree 1310 1311 Sequence of bytecodes that access a free variable (note that 'free' in this 1312 context refers to names in the current scope that are referenced by inner 1313 scopes or names in outer scopes that are referenced from this scope. It does 1314 *not* include references to global or builtin scopes). 1315 1316 1317.. data:: hasname 1318 1319 Sequence of bytecodes that access an attribute by name. 1320 1321 1322.. data:: hasjrel 1323 1324 Sequence of bytecodes that have a relative jump target. 1325 1326 1327.. data:: hasjabs 1328 1329 Sequence of bytecodes that have an absolute jump target. 1330 1331 1332.. data:: haslocal 1333 1334 Sequence of bytecodes that access a local variable. 1335 1336 1337.. data:: hascompare 1338 1339 Sequence of bytecodes of Boolean operations. 1340