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