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:: POP_FINALLY (preserve_tos) 710 711 Cleans up the value stack and the block stack. If *preserve_tos* is not 712 ``0`` TOS first is popped from the stack and pushed on the stack after 713 performing other stack operations: 714 715 * If TOS is ``NULL`` or an integer (pushed by :opcode:`BEGIN_FINALLY` 716 or :opcode:`CALL_FINALLY`) it is popped from the stack. 717 * If TOS is an exception type (pushed when an exception has been raised) 718 6 values are popped from the stack, the last three popped values are 719 used to restore the exception state. An exception handler block is 720 removed from the block stack. 721 722 It is similar to :opcode:`END_FINALLY`, but doesn't change the bytecode 723 counter nor raise an exception. Used for implementing :keyword:`break`, 724 :keyword:`continue` and :keyword:`return` in the :keyword:`finally` block. 725 726 .. versionadded:: 3.8 727 728 729.. opcode:: BEGIN_FINALLY 730 731 Pushes ``NULL`` onto the stack for using it in :opcode:`END_FINALLY`, 732 :opcode:`POP_FINALLY`, :opcode:`WITH_CLEANUP_START` and 733 :opcode:`WITH_CLEANUP_FINISH`. Starts the :keyword:`finally` block. 734 735 .. versionadded:: 3.8 736 737 738.. opcode:: END_FINALLY 739 740 Terminates a :keyword:`finally` clause. The interpreter recalls whether the 741 exception has to be re-raised or execution has to be continued depending on 742 the value of TOS. 743 744 * If TOS is ``NULL`` (pushed by :opcode:`BEGIN_FINALLY`) continue from 745 the next instruction. TOS is popped. 746 * If TOS is an integer (pushed by :opcode:`CALL_FINALLY`), sets the 747 bytecode counter to TOS. TOS is popped. 748 * If TOS is an exception type (pushed when an exception has been raised) 749 6 values are popped from the stack, the first three popped values are 750 used to re-raise the exception and the last three popped values are used 751 to restore the exception state. An exception handler block is removed 752 from the block stack. 753 754 755.. opcode:: LOAD_BUILD_CLASS 756 757 Pushes :func:`builtins.__build_class__` onto the stack. It is later called 758 by :opcode:`CALL_FUNCTION` to construct a class. 759 760 761.. opcode:: SETUP_WITH (delta) 762 763 This opcode performs several operations before a with block starts. First, 764 it loads :meth:`~object.__exit__` from the context manager and pushes it onto 765 the stack for later use by :opcode:`WITH_CLEANUP_START`. Then, 766 :meth:`~object.__enter__` is called, and a finally block pointing to *delta* 767 is pushed. Finally, the result of calling the ``__enter__()`` method is pushed onto 768 the stack. The next opcode will either ignore it (:opcode:`POP_TOP`), or 769 store it in (a) variable(s) (:opcode:`STORE_FAST`, :opcode:`STORE_NAME`, or 770 :opcode:`UNPACK_SEQUENCE`). 771 772 .. versionadded:: 3.2 773 774 775.. opcode:: WITH_CLEANUP_START 776 777 Starts cleaning up the stack when a :keyword:`with` statement block exits. 778 779 At the top of the stack are either ``NULL`` (pushed by 780 :opcode:`BEGIN_FINALLY`) or 6 values pushed if an exception has been 781 raised in the with block. Below is the context manager's 782 :meth:`~object.__exit__` or :meth:`~object.__aexit__` bound method. 783 784 If TOS is ``NULL``, calls ``SECOND(None, None, None)``, 785 removes the function from the stack, leaving TOS, and pushes ``None`` 786 to the stack. Otherwise calls ``SEVENTH(TOP, SECOND, THIRD)``, 787 shifts the bottom 3 values of the stack down, replaces the empty spot 788 with ``NULL`` and pushes TOS. Finally pushes the result of the call. 789 790 791.. opcode:: WITH_CLEANUP_FINISH 792 793 Finishes cleaning up the stack when a :keyword:`with` statement block exits. 794 795 TOS is result of ``__exit__()`` or ``__aexit__()`` function call pushed 796 by :opcode:`WITH_CLEANUP_START`. SECOND is ``None`` or an exception type 797 (pushed when an exception has been raised). 798 799 Pops two values from the stack. If SECOND is not None and TOS is true 800 unwinds the EXCEPT_HANDLER block which was created when the exception 801 was caught and pushes ``NULL`` to the stack. 802 803 804All of the following opcodes use their arguments. 805 806.. opcode:: STORE_NAME (namei) 807 808 Implements ``name = TOS``. *namei* is the index of *name* in the attribute 809 :attr:`co_names` of the code object. The compiler tries to use 810 :opcode:`STORE_FAST` or :opcode:`STORE_GLOBAL` if possible. 811 812 813.. opcode:: DELETE_NAME (namei) 814 815 Implements ``del name``, where *namei* is the index into :attr:`co_names` 816 attribute of the code object. 817 818 819.. opcode:: UNPACK_SEQUENCE (count) 820 821 Unpacks TOS into *count* individual values, which are put onto the stack 822 right-to-left. 823 824 825.. opcode:: UNPACK_EX (counts) 826 827 Implements assignment with a starred target: Unpacks an iterable in TOS into 828 individual values, where the total number of values can be smaller than the 829 number of items in the iterable: one of the new values will be a list of all 830 leftover items. 831 832 The low byte of *counts* is the number of values before the list value, the 833 high byte of *counts* the number of values after it. The resulting values 834 are put onto the stack right-to-left. 835 836 837.. opcode:: STORE_ATTR (namei) 838 839 Implements ``TOS.name = TOS1``, where *namei* is the index of name in 840 :attr:`co_names`. 841 842 843.. opcode:: DELETE_ATTR (namei) 844 845 Implements ``del TOS.name``, using *namei* as index into :attr:`co_names`. 846 847 848.. opcode:: STORE_GLOBAL (namei) 849 850 Works as :opcode:`STORE_NAME`, but stores the name as a global. 851 852 853.. opcode:: DELETE_GLOBAL (namei) 854 855 Works as :opcode:`DELETE_NAME`, but deletes a global name. 856 857 858.. opcode:: LOAD_CONST (consti) 859 860 Pushes ``co_consts[consti]`` onto the stack. 861 862 863.. opcode:: LOAD_NAME (namei) 864 865 Pushes the value associated with ``co_names[namei]`` onto the stack. 866 867 868.. opcode:: BUILD_TUPLE (count) 869 870 Creates a tuple consuming *count* items from the stack, and pushes the 871 resulting tuple onto the stack. 872 873 874.. opcode:: BUILD_LIST (count) 875 876 Works as :opcode:`BUILD_TUPLE`, but creates a list. 877 878 879.. opcode:: BUILD_SET (count) 880 881 Works as :opcode:`BUILD_TUPLE`, but creates a set. 882 883 884.. opcode:: BUILD_MAP (count) 885 886 Pushes a new dictionary object onto the stack. Pops ``2 * count`` items 887 so that the dictionary holds *count* entries: 888 ``{..., TOS3: TOS2, TOS1: TOS}``. 889 890 .. versionchanged:: 3.5 891 The dictionary is created from stack items instead of creating an 892 empty dictionary pre-sized to hold *count* items. 893 894 895.. opcode:: BUILD_CONST_KEY_MAP (count) 896 897 The version of :opcode:`BUILD_MAP` specialized for constant keys. Pops the 898 top element on the stack which contains a tuple of keys, then starting from 899 ``TOS1``, pops *count* values to form values in the built dictionary. 900 901 .. versionadded:: 3.6 902 903 904.. opcode:: BUILD_STRING (count) 905 906 Concatenates *count* strings from the stack and pushes the resulting string 907 onto the stack. 908 909 .. versionadded:: 3.6 910 911 912.. opcode:: BUILD_TUPLE_UNPACK (count) 913 914 Pops *count* iterables from the stack, joins them in a single tuple, 915 and pushes the result. Implements iterable unpacking in tuple 916 displays ``(*x, *y, *z)``. 917 918 .. versionadded:: 3.5 919 920 921.. opcode:: BUILD_TUPLE_UNPACK_WITH_CALL (count) 922 923 This is similar to :opcode:`BUILD_TUPLE_UNPACK`, 924 but is used for ``f(*x, *y, *z)`` call syntax. The stack item at position 925 ``count + 1`` should be the corresponding callable ``f``. 926 927 .. versionadded:: 3.6 928 929 930.. opcode:: BUILD_LIST_UNPACK (count) 931 932 This is similar to :opcode:`BUILD_TUPLE_UNPACK`, but pushes a list 933 instead of tuple. Implements iterable unpacking in list 934 displays ``[*x, *y, *z]``. 935 936 .. versionadded:: 3.5 937 938 939.. opcode:: BUILD_SET_UNPACK (count) 940 941 This is similar to :opcode:`BUILD_TUPLE_UNPACK`, but pushes a set 942 instead of tuple. Implements iterable unpacking in set 943 displays ``{*x, *y, *z}``. 944 945 .. versionadded:: 3.5 946 947 948.. opcode:: BUILD_MAP_UNPACK (count) 949 950 Pops *count* mappings from the stack, merges them into a single dictionary, 951 and pushes the result. Implements dictionary unpacking in dictionary 952 displays ``{**x, **y, **z}``. 953 954 .. versionadded:: 3.5 955 956 957.. opcode:: BUILD_MAP_UNPACK_WITH_CALL (count) 958 959 This is similar to :opcode:`BUILD_MAP_UNPACK`, 960 but is used for ``f(**x, **y, **z)`` call syntax. The stack item at 961 position ``count + 2`` should be the corresponding callable ``f``. 962 963 .. versionadded:: 3.5 964 .. versionchanged:: 3.6 965 The position of the callable is determined by adding 2 to the opcode 966 argument instead of encoding it in the second byte of the argument. 967 968 969.. opcode:: LOAD_ATTR (namei) 970 971 Replaces TOS with ``getattr(TOS, co_names[namei])``. 972 973 974.. opcode:: COMPARE_OP (opname) 975 976 Performs a Boolean operation. The operation name can be found in 977 ``cmp_op[opname]``. 978 979 980.. opcode:: IMPORT_NAME (namei) 981 982 Imports the module ``co_names[namei]``. TOS and TOS1 are popped and provide 983 the *fromlist* and *level* arguments of :func:`__import__`. The module 984 object is pushed onto the stack. The current namespace is not affected: for 985 a proper import statement, a subsequent :opcode:`STORE_FAST` instruction 986 modifies the namespace. 987 988 989.. opcode:: IMPORT_FROM (namei) 990 991 Loads the attribute ``co_names[namei]`` from the module found in TOS. The 992 resulting object is pushed onto the stack, to be subsequently stored by a 993 :opcode:`STORE_FAST` instruction. 994 995 996.. opcode:: JUMP_FORWARD (delta) 997 998 Increments bytecode counter by *delta*. 999 1000 1001.. opcode:: POP_JUMP_IF_TRUE (target) 1002 1003 If TOS is true, sets the bytecode counter to *target*. TOS is popped. 1004 1005 .. versionadded:: 3.1 1006 1007 1008.. opcode:: POP_JUMP_IF_FALSE (target) 1009 1010 If TOS is false, sets the bytecode counter to *target*. TOS is popped. 1011 1012 .. versionadded:: 3.1 1013 1014 1015.. opcode:: JUMP_IF_TRUE_OR_POP (target) 1016 1017 If TOS is true, sets the bytecode counter to *target* and leaves TOS on the 1018 stack. Otherwise (TOS is false), TOS is popped. 1019 1020 .. versionadded:: 3.1 1021 1022 1023.. opcode:: JUMP_IF_FALSE_OR_POP (target) 1024 1025 If TOS is false, sets the bytecode counter to *target* and leaves TOS on the 1026 stack. Otherwise (TOS is true), TOS is popped. 1027 1028 .. versionadded:: 3.1 1029 1030 1031.. opcode:: JUMP_ABSOLUTE (target) 1032 1033 Set bytecode counter to *target*. 1034 1035 1036.. opcode:: FOR_ITER (delta) 1037 1038 TOS is an :term:`iterator`. Call its :meth:`~iterator.__next__` method. If 1039 this yields a new value, push it on the stack (leaving the iterator below 1040 it). If the iterator indicates it is exhausted TOS is popped, and the byte 1041 code counter is incremented by *delta*. 1042 1043 1044.. opcode:: LOAD_GLOBAL (namei) 1045 1046 Loads the global named ``co_names[namei]`` onto the stack. 1047 1048 1049.. opcode:: SETUP_FINALLY (delta) 1050 1051 Pushes a try block from a try-finally or try-except clause onto the block 1052 stack. *delta* points to the finally block or the first except block. 1053 1054 1055.. opcode:: CALL_FINALLY (delta) 1056 1057 Pushes the address of the next instruction onto the stack and increments 1058 bytecode counter by *delta*. Used for calling the finally block as a 1059 "subroutine". 1060 1061 .. versionadded:: 3.8 1062 1063 1064.. opcode:: LOAD_FAST (var_num) 1065 1066 Pushes a reference to the local ``co_varnames[var_num]`` onto the stack. 1067 1068 1069.. opcode:: STORE_FAST (var_num) 1070 1071 Stores TOS into the local ``co_varnames[var_num]``. 1072 1073 1074.. opcode:: DELETE_FAST (var_num) 1075 1076 Deletes local ``co_varnames[var_num]``. 1077 1078 1079.. opcode:: LOAD_CLOSURE (i) 1080 1081 Pushes a reference to the cell contained in slot *i* of the cell and free 1082 variable storage. The name of the variable is ``co_cellvars[i]`` if *i* is 1083 less than the length of *co_cellvars*. Otherwise it is ``co_freevars[i - 1084 len(co_cellvars)]``. 1085 1086 1087.. opcode:: LOAD_DEREF (i) 1088 1089 Loads the cell contained in slot *i* of the cell and free variable storage. 1090 Pushes a reference to the object the cell contains on the stack. 1091 1092 1093.. opcode:: LOAD_CLASSDEREF (i) 1094 1095 Much like :opcode:`LOAD_DEREF` but first checks the locals dictionary before 1096 consulting the cell. This is used for loading free variables in class 1097 bodies. 1098 1099 .. versionadded:: 3.4 1100 1101 1102.. opcode:: STORE_DEREF (i) 1103 1104 Stores TOS into the cell contained in slot *i* of the cell and free variable 1105 storage. 1106 1107 1108.. opcode:: DELETE_DEREF (i) 1109 1110 Empties the cell contained in slot *i* of the cell and free variable storage. 1111 Used by the :keyword:`del` statement. 1112 1113 .. versionadded:: 3.2 1114 1115 1116.. opcode:: RAISE_VARARGS (argc) 1117 1118 Raises an exception using one of the 3 forms of the ``raise`` statement, 1119 depending on the value of *argc*: 1120 1121 * 0: ``raise`` (re-raise previous exception) 1122 * 1: ``raise TOS`` (raise exception instance or type at ``TOS``) 1123 * 2: ``raise TOS1 from TOS`` (raise exception instance or type at ``TOS1`` 1124 with ``__cause__`` set to ``TOS``) 1125 1126 1127.. opcode:: CALL_FUNCTION (argc) 1128 1129 Calls a callable object with positional arguments. 1130 *argc* indicates the number of positional arguments. 1131 The top of the stack contains positional arguments, with the right-most 1132 argument on top. Below the arguments is a callable object to call. 1133 ``CALL_FUNCTION`` pops all arguments and the callable object off the stack, 1134 calls the callable object with those arguments, and pushes the return value 1135 returned by the callable object. 1136 1137 .. versionchanged:: 3.6 1138 This opcode is used only for calls with positional arguments. 1139 1140 1141.. opcode:: CALL_FUNCTION_KW (argc) 1142 1143 Calls a callable object with positional (if any) and keyword arguments. 1144 *argc* indicates the total number of positional and keyword arguments. 1145 The top element on the stack contains a tuple of keyword argument names. 1146 Below that are keyword arguments in the order corresponding to the tuple. 1147 Below that are positional arguments, with the right-most parameter on 1148 top. Below the arguments is a callable object to call. 1149 ``CALL_FUNCTION_KW`` pops all arguments and the callable object off the stack, 1150 calls the callable object with those arguments, and pushes the return value 1151 returned by the callable object. 1152 1153 .. versionchanged:: 3.6 1154 Keyword arguments are packed in a tuple instead of a dictionary, 1155 *argc* indicates the total number of arguments. 1156 1157 1158.. opcode:: CALL_FUNCTION_EX (flags) 1159 1160 Calls a callable object with variable set of positional and keyword 1161 arguments. If the lowest bit of *flags* is set, the top of the stack 1162 contains a mapping object containing additional keyword arguments. 1163 Below that is an iterable object containing positional arguments and 1164 a callable object to call. :opcode:`BUILD_MAP_UNPACK_WITH_CALL` and 1165 :opcode:`BUILD_TUPLE_UNPACK_WITH_CALL` can be used for merging multiple 1166 mapping objects and iterables containing arguments. 1167 Before the callable is called, the mapping object and iterable object 1168 are each "unpacked" and their contents passed in as keyword and 1169 positional arguments respectively. 1170 ``CALL_FUNCTION_EX`` pops all arguments and the callable object off the stack, 1171 calls the callable object with those arguments, and pushes the return value 1172 returned by the callable object. 1173 1174 .. versionadded:: 3.6 1175 1176 1177.. opcode:: LOAD_METHOD (namei) 1178 1179 Loads a method named ``co_names[namei]`` from the TOS object. TOS is popped. 1180 This bytecode distinguishes two cases: if TOS has a method with the correct 1181 name, the bytecode pushes the unbound method and TOS. TOS will be used as 1182 the first argument (``self``) by :opcode:`CALL_METHOD` when calling the 1183 unbound method. Otherwise, ``NULL`` and the object return by the attribute 1184 lookup are pushed. 1185 1186 .. versionadded:: 3.7 1187 1188 1189.. opcode:: CALL_METHOD (argc) 1190 1191 Calls a method. *argc* is the number of positional arguments. 1192 Keyword arguments are not supported. This opcode is designed to be used 1193 with :opcode:`LOAD_METHOD`. Positional arguments are on top of the stack. 1194 Below them, the two items described in :opcode:`LOAD_METHOD` are on the 1195 stack (either ``self`` and an unbound method object or ``NULL`` and an 1196 arbitrary callable). All of them are popped and the return value is pushed. 1197 1198 .. versionadded:: 3.7 1199 1200 1201.. opcode:: MAKE_FUNCTION (flags) 1202 1203 Pushes a new function object on the stack. From bottom to top, the consumed 1204 stack must consist of values if the argument carries a specified flag value 1205 1206 * ``0x01`` a tuple of default values for positional-only and 1207 positional-or-keyword parameters in positional order 1208 * ``0x02`` a dictionary of keyword-only parameters' default values 1209 * ``0x04`` an annotation dictionary 1210 * ``0x08`` a tuple containing cells for free variables, making a closure 1211 * the code associated with the function (at TOS1) 1212 * the :term:`qualified name` of the function (at TOS) 1213 1214 1215.. opcode:: BUILD_SLICE (argc) 1216 1217 .. index:: builtin: slice 1218 1219 Pushes a slice object on the stack. *argc* must be 2 or 3. If it is 2, 1220 ``slice(TOS1, TOS)`` is pushed; if it is 3, ``slice(TOS2, TOS1, TOS)`` is 1221 pushed. See the :func:`slice` built-in function for more information. 1222 1223 1224.. opcode:: EXTENDED_ARG (ext) 1225 1226 Prefixes any opcode which has an argument too big to fit into the default one 1227 byte. *ext* holds an additional byte which act as higher bits in the argument. 1228 For each opcode, at most three prefixal ``EXTENDED_ARG`` are allowed, forming 1229 an argument from two-byte to four-byte. 1230 1231 1232.. opcode:: FORMAT_VALUE (flags) 1233 1234 Used for implementing formatted literal strings (f-strings). Pops 1235 an optional *fmt_spec* from the stack, then a required *value*. 1236 *flags* is interpreted as follows: 1237 1238 * ``(flags & 0x03) == 0x00``: *value* is formatted as-is. 1239 * ``(flags & 0x03) == 0x01``: call :func:`str` on *value* before 1240 formatting it. 1241 * ``(flags & 0x03) == 0x02``: call :func:`repr` on *value* before 1242 formatting it. 1243 * ``(flags & 0x03) == 0x03``: call :func:`ascii` on *value* before 1244 formatting it. 1245 * ``(flags & 0x04) == 0x04``: pop *fmt_spec* from the stack and use 1246 it, else use an empty *fmt_spec*. 1247 1248 Formatting is performed using :c:func:`PyObject_Format`. The 1249 result is pushed on the stack. 1250 1251 .. versionadded:: 3.6 1252 1253 1254.. opcode:: HAVE_ARGUMENT 1255 1256 This is not really an opcode. It identifies the dividing line between 1257 opcodes which don't use their argument and those that do 1258 (``< HAVE_ARGUMENT`` and ``>= HAVE_ARGUMENT``, respectively). 1259 1260 .. versionchanged:: 3.6 1261 Now every instruction has an argument, but opcodes ``< HAVE_ARGUMENT`` 1262 ignore it. Before, only opcodes ``>= HAVE_ARGUMENT`` had an argument. 1263 1264 1265.. _opcode_collections: 1266 1267Opcode collections 1268------------------ 1269 1270These collections are provided for automatic introspection of bytecode 1271instructions: 1272 1273.. data:: opname 1274 1275 Sequence of operation names, indexable using the bytecode. 1276 1277 1278.. data:: opmap 1279 1280 Dictionary mapping operation names to bytecodes. 1281 1282 1283.. data:: cmp_op 1284 1285 Sequence of all compare operation names. 1286 1287 1288.. data:: hasconst 1289 1290 Sequence of bytecodes that access a constant. 1291 1292 1293.. data:: hasfree 1294 1295 Sequence of bytecodes that access a free variable (note that 'free' in this 1296 context refers to names in the current scope that are referenced by inner 1297 scopes or names in outer scopes that are referenced from this scope. It does 1298 *not* include references to global or builtin scopes). 1299 1300 1301.. data:: hasname 1302 1303 Sequence of bytecodes that access an attribute by name. 1304 1305 1306.. data:: hasjrel 1307 1308 Sequence of bytecodes that have a relative jump target. 1309 1310 1311.. data:: hasjabs 1312 1313 Sequence of bytecodes that have an absolute jump target. 1314 1315 1316.. data:: haslocal 1317 1318 Sequence of bytecodes that access a local variable. 1319 1320 1321.. data:: hascompare 1322 1323 Sequence of bytecodes of Boolean operations. 1324