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