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 code object *code* which are jump targets, and
248   return a list of these offsets.
249
250
251.. function:: stack_effect(opcode, [oparg])
252
253   Compute the stack effect of *opcode* with argument *oparg*.
254
255   .. versionadded:: 3.4
256
257.. _bytecodes:
258
259Python Bytecode Instructions
260----------------------------
261
262The :func:`get_instructions` function and :class:`Bytecode` class provide
263details of bytecode instructions as :class:`Instruction` instances:
264
265.. class:: Instruction
266
267   Details for a bytecode operation
268
269   .. data:: opcode
270
271      numeric code for operation, corresponding to the opcode values listed
272      below and the bytecode values in the :ref:`opcode_collections`.
273
274
275   .. data:: opname
276
277      human readable name for operation
278
279
280   .. data:: arg
281
282      numeric argument to operation (if any), otherwise ``None``
283
284
285   .. data:: argval
286
287      resolved arg value (if known), otherwise same as arg
288
289
290   .. data:: argrepr
291
292      human readable description of operation argument
293
294
295   .. data:: offset
296
297      start index of operation within bytecode sequence
298
299
300   .. data:: starts_line
301
302      line started by this opcode (if any), otherwise ``None``
303
304
305   .. data:: is_jump_target
306
307      ``True`` if other code jumps to here, otherwise ``False``
308
309   .. versionadded:: 3.4
310
311
312The Python compiler currently generates the following bytecode instructions.
313
314
315**General instructions**
316
317.. opcode:: NOP
318
319   Do nothing code.  Used as a placeholder by the bytecode optimizer.
320
321
322.. opcode:: POP_TOP
323
324   Removes the top-of-stack (TOS) item.
325
326
327.. opcode:: ROT_TWO
328
329   Swaps the two top-most stack items.
330
331
332.. opcode:: ROT_THREE
333
334   Lifts second and third stack item one position up, moves top down to position
335   three.
336
337
338.. opcode:: DUP_TOP
339
340   Duplicates the reference on top of the stack.
341
342   .. versionadded:: 3.2
343
344
345.. opcode:: DUP_TOP_TWO
346
347   Duplicates the two references on top of the stack, leaving them in the
348   same order.
349
350   .. versionadded:: 3.2
351
352
353**Unary operations**
354
355Unary operations take the top of the stack, apply the operation, and push the
356result back on the stack.
357
358.. opcode:: UNARY_POSITIVE
359
360   Implements ``TOS = +TOS``.
361
362
363.. opcode:: UNARY_NEGATIVE
364
365   Implements ``TOS = -TOS``.
366
367
368.. opcode:: UNARY_NOT
369
370   Implements ``TOS = not TOS``.
371
372
373.. opcode:: UNARY_INVERT
374
375   Implements ``TOS = ~TOS``.
376
377
378.. opcode:: GET_ITER
379
380   Implements ``TOS = iter(TOS)``.
381
382
383.. opcode:: GET_YIELD_FROM_ITER
384
385   If ``TOS`` is a :term:`generator iterator` or :term:`coroutine` object
386   it is left as is.  Otherwise, implements ``TOS = iter(TOS)``.
387
388   .. versionadded:: 3.5
389
390
391**Binary operations**
392
393Binary operations remove the top of the stack (TOS) and the second top-most
394stack item (TOS1) from the stack.  They perform the operation, and put the
395result back on the stack.
396
397.. opcode:: BINARY_POWER
398
399   Implements ``TOS = TOS1 ** TOS``.
400
401
402.. opcode:: BINARY_MULTIPLY
403
404   Implements ``TOS = TOS1 * TOS``.
405
406
407.. opcode:: BINARY_MATRIX_MULTIPLY
408
409   Implements ``TOS = TOS1 @ TOS``.
410
411   .. versionadded:: 3.5
412
413
414.. opcode:: BINARY_FLOOR_DIVIDE
415
416   Implements ``TOS = TOS1 // TOS``.
417
418
419.. opcode:: BINARY_TRUE_DIVIDE
420
421   Implements ``TOS = TOS1 / TOS``.
422
423
424.. opcode:: BINARY_MODULO
425
426   Implements ``TOS = TOS1 % TOS``.
427
428
429.. opcode:: BINARY_ADD
430
431   Implements ``TOS = TOS1 + TOS``.
432
433
434.. opcode:: BINARY_SUBTRACT
435
436   Implements ``TOS = TOS1 - TOS``.
437
438
439.. opcode:: BINARY_SUBSCR
440
441   Implements ``TOS = TOS1[TOS]``.
442
443
444.. opcode:: BINARY_LSHIFT
445
446   Implements ``TOS = TOS1 << TOS``.
447
448
449.. opcode:: BINARY_RSHIFT
450
451   Implements ``TOS = TOS1 >> TOS``.
452
453
454.. opcode:: BINARY_AND
455
456   Implements ``TOS = TOS1 & TOS``.
457
458
459.. opcode:: BINARY_XOR
460
461   Implements ``TOS = TOS1 ^ TOS``.
462
463
464.. opcode:: BINARY_OR
465
466   Implements ``TOS = TOS1 | TOS``.
467
468
469**In-place operations**
470
471In-place operations are like binary operations, in that they remove TOS and
472TOS1, and push the result back on the stack, but the operation is done in-place
473when TOS1 supports it, and the resulting TOS may be (but does not have to be)
474the original TOS1.
475
476.. opcode:: INPLACE_POWER
477
478   Implements in-place ``TOS = TOS1 ** TOS``.
479
480
481.. opcode:: INPLACE_MULTIPLY
482
483   Implements in-place ``TOS = TOS1 * TOS``.
484
485
486.. opcode:: INPLACE_MATRIX_MULTIPLY
487
488   Implements in-place ``TOS = TOS1 @ TOS``.
489
490   .. versionadded:: 3.5
491
492
493.. opcode:: INPLACE_FLOOR_DIVIDE
494
495   Implements in-place ``TOS = TOS1 // TOS``.
496
497
498.. opcode:: INPLACE_TRUE_DIVIDE
499
500   Implements in-place ``TOS = TOS1 / TOS``.
501
502
503.. opcode:: INPLACE_MODULO
504
505   Implements in-place ``TOS = TOS1 % TOS``.
506
507
508.. opcode:: INPLACE_ADD
509
510   Implements in-place ``TOS = TOS1 + TOS``.
511
512
513.. opcode:: INPLACE_SUBTRACT
514
515   Implements in-place ``TOS = TOS1 - TOS``.
516
517
518.. opcode:: INPLACE_LSHIFT
519
520   Implements in-place ``TOS = TOS1 << TOS``.
521
522
523.. opcode:: INPLACE_RSHIFT
524
525   Implements in-place ``TOS = TOS1 >> TOS``.
526
527
528.. opcode:: INPLACE_AND
529
530   Implements in-place ``TOS = TOS1 & TOS``.
531
532
533.. opcode:: INPLACE_XOR
534
535   Implements in-place ``TOS = TOS1 ^ TOS``.
536
537
538.. opcode:: INPLACE_OR
539
540   Implements in-place ``TOS = TOS1 | TOS``.
541
542
543.. opcode:: STORE_SUBSCR
544
545   Implements ``TOS1[TOS] = TOS2``.
546
547
548.. opcode:: DELETE_SUBSCR
549
550   Implements ``del TOS1[TOS]``.
551
552
553**Coroutine opcodes**
554
555.. opcode:: GET_AWAITABLE
556
557   Implements ``TOS = get_awaitable(TOS)``, where ``get_awaitable(o)``
558   returns ``o`` if ``o`` is a coroutine object or a generator object with
559   the CO_ITERABLE_COROUTINE flag, or resolves
560   ``o.__await__``.
561
562   .. versionadded:: 3.5
563
564
565.. opcode:: GET_AITER
566
567   Implements ``TOS = TOS.__aiter__()``.
568
569   .. versionadded:: 3.5
570   .. versionchanged:: 3.7
571      Returning awaitable objects from ``__aiter__`` is no longer
572      supported.
573
574
575.. opcode:: GET_ANEXT
576
577   Implements ``PUSH(get_awaitable(TOS.__anext__()))``.  See ``GET_AWAITABLE``
578   for details about ``get_awaitable``
579
580   .. versionadded:: 3.5
581
582
583.. opcode:: BEFORE_ASYNC_WITH
584
585   Resolves ``__aenter__`` and ``__aexit__`` from the object on top of the
586   stack.  Pushes ``__aexit__`` and result of ``__aenter__()`` to the stack.
587
588   .. versionadded:: 3.5
589
590
591.. opcode:: SETUP_ASYNC_WITH
592
593   Creates a new frame object.
594
595   .. versionadded:: 3.5
596
597
598
599**Miscellaneous opcodes**
600
601.. opcode:: PRINT_EXPR
602
603   Implements the expression statement for the interactive mode.  TOS is removed
604   from the stack and printed.  In non-interactive mode, an expression statement
605   is terminated with :opcode:`POP_TOP`.
606
607
608.. opcode:: BREAK_LOOP
609
610   Terminates a loop due to a :keyword:`break` statement.
611
612
613.. opcode:: CONTINUE_LOOP (target)
614
615   Continues a loop due to a :keyword:`continue` statement.  *target* is the
616   address to jump to (which should be a :opcode:`FOR_ITER` instruction).
617
618
619.. opcode:: SET_ADD (i)
620
621   Calls ``set.add(TOS1[-i], TOS)``.  Used to implement set comprehensions.
622
623
624.. opcode:: LIST_APPEND (i)
625
626   Calls ``list.append(TOS[-i], TOS)``.  Used to implement list comprehensions.
627
628
629.. opcode:: MAP_ADD (i)
630
631   Calls ``dict.setitem(TOS1[-i], TOS, TOS1)``.  Used to implement dict
632   comprehensions.
633
634   .. versionadded:: 3.1
635
636For all of the :opcode:`SET_ADD`, :opcode:`LIST_APPEND` and :opcode:`MAP_ADD`
637instructions, while the added value or key/value pair is popped off, the
638container object remains on the stack so that it is available for further
639iterations of the loop.
640
641
642.. opcode:: RETURN_VALUE
643
644   Returns with TOS to the caller of the function.
645
646
647.. opcode:: YIELD_VALUE
648
649   Pops TOS and yields it from a :term:`generator`.
650
651
652.. opcode:: YIELD_FROM
653
654   Pops TOS and delegates to it as a subiterator from a :term:`generator`.
655
656   .. versionadded:: 3.3
657
658
659.. opcode:: SETUP_ANNOTATIONS
660
661   Checks whether ``__annotations__`` is defined in ``locals()``, if not it is
662   set up to an empty ``dict``. This opcode is only emitted if a class
663   or module body contains :term:`variable annotations <variable annotation>`
664   statically.
665
666   .. versionadded:: 3.6
667
668
669.. opcode:: IMPORT_STAR
670
671   Loads all symbols not starting with ``'_'`` directly from the module TOS to
672   the local namespace. The module is popped after loading all names. This
673   opcode implements ``from module import *``.
674
675
676.. opcode:: POP_BLOCK
677
678   Removes one block from the block stack.  Per frame, there is a stack of
679   blocks, denoting nested loops, try statements, and such.
680
681
682.. opcode:: POP_EXCEPT
683
684   Removes one block from the block stack. The popped block must be an exception
685   handler block, as implicitly created when entering an except handler.  In
686   addition to popping extraneous values from the frame stack, the last three
687   popped values are used to restore the exception state.
688
689
690.. opcode:: END_FINALLY
691
692   Terminates a :keyword:`finally` clause.  The interpreter recalls whether the
693   exception has to be re-raised, or whether the function returns, and continues
694   with the outer-next block.
695
696
697.. opcode:: LOAD_BUILD_CLASS
698
699   Pushes :func:`builtins.__build_class__` onto the stack.  It is later called
700   by :opcode:`CALL_FUNCTION` to construct a class.
701
702
703.. opcode:: SETUP_WITH (delta)
704
705   This opcode performs several operations before a with block starts.  First,
706   it loads :meth:`~object.__exit__` from the context manager and pushes it onto
707   the stack for later use by :opcode:`WITH_CLEANUP`.  Then,
708   :meth:`~object.__enter__` is called, and a finally block pointing to *delta*
709   is pushed.  Finally, the result of calling the enter method is pushed onto
710   the stack.  The next opcode will either ignore it (:opcode:`POP_TOP`), or
711   store it in (a) variable(s) (:opcode:`STORE_FAST`, :opcode:`STORE_NAME`, or
712   :opcode:`UNPACK_SEQUENCE`).
713
714   .. versionadded:: 3.2
715
716
717.. opcode:: WITH_CLEANUP_START
718
719   Cleans up the stack when a :keyword:`with` statement block exits.  TOS is the
720   context manager's :meth:`__exit__` bound method. Below TOS are 1--3 values
721   indicating how/why the finally clause was entered:
722
723   * SECOND = ``None``
724   * (SECOND, THIRD) = (``WHY_{RETURN,CONTINUE}``), retval
725   * SECOND = ``WHY_*``; no retval below it
726   * (SECOND, THIRD, FOURTH) = exc_info()
727
728   In the last case, ``TOS(SECOND, THIRD, FOURTH)`` is called, otherwise
729   ``TOS(None, None, None)``.  Pushes SECOND and result of the call
730   to the stack.
731
732
733.. opcode:: WITH_CLEANUP_FINISH
734
735   Pops exception type and result of 'exit' function call from the stack.
736
737   If the stack represents an exception, *and* the function call returns a
738   'true' value, this information is "zapped" and replaced with a single
739   ``WHY_SILENCED`` to prevent :opcode:`END_FINALLY` from re-raising the
740   exception.  (But non-local gotos will still be resumed.)
741
742   .. XXX explain the WHY stuff!
743
744
745All of the following opcodes use their arguments.
746
747.. opcode:: STORE_NAME (namei)
748
749   Implements ``name = TOS``. *namei* is the index of *name* in the attribute
750   :attr:`co_names` of the code object. The compiler tries to use
751   :opcode:`STORE_FAST` or :opcode:`STORE_GLOBAL` if possible.
752
753
754.. opcode:: DELETE_NAME (namei)
755
756   Implements ``del name``, where *namei* is the index into :attr:`co_names`
757   attribute of the code object.
758
759
760.. opcode:: UNPACK_SEQUENCE (count)
761
762   Unpacks TOS into *count* individual values, which are put onto the stack
763   right-to-left.
764
765
766.. opcode:: UNPACK_EX (counts)
767
768   Implements assignment with a starred target: Unpacks an iterable in TOS into
769   individual values, where the total number of values can be smaller than the
770   number of items in the iterable: one of the new values will be a list of all
771   leftover items.
772
773   The low byte of *counts* is the number of values before the list value, the
774   high byte of *counts* the number of values after it.  The resulting values
775   are put onto the stack right-to-left.
776
777
778.. opcode:: STORE_ATTR (namei)
779
780   Implements ``TOS.name = TOS1``, where *namei* is the index of name in
781   :attr:`co_names`.
782
783
784.. opcode:: DELETE_ATTR (namei)
785
786   Implements ``del TOS.name``, using *namei* as index into :attr:`co_names`.
787
788
789.. opcode:: STORE_GLOBAL (namei)
790
791   Works as :opcode:`STORE_NAME`, but stores the name as a global.
792
793
794.. opcode:: DELETE_GLOBAL (namei)
795
796   Works as :opcode:`DELETE_NAME`, but deletes a global name.
797
798
799.. opcode:: LOAD_CONST (consti)
800
801   Pushes ``co_consts[consti]`` onto the stack.
802
803
804.. opcode:: LOAD_NAME (namei)
805
806   Pushes the value associated with ``co_names[namei]`` onto the stack.
807
808
809.. opcode:: BUILD_TUPLE (count)
810
811   Creates a tuple consuming *count* items from the stack, and pushes the
812   resulting tuple onto the stack.
813
814
815.. opcode:: BUILD_LIST (count)
816
817   Works as :opcode:`BUILD_TUPLE`, but creates a list.
818
819
820.. opcode:: BUILD_SET (count)
821
822   Works as :opcode:`BUILD_TUPLE`, but creates a set.
823
824
825.. opcode:: BUILD_MAP (count)
826
827   Pushes a new dictionary object onto the stack.  Pops ``2 * count`` items
828   so that the dictionary holds *count* entries:
829   ``{..., TOS3: TOS2, TOS1: TOS}``.
830
831   .. versionchanged:: 3.5
832      The dictionary is created from stack items instead of creating an
833      empty dictionary pre-sized to hold *count* items.
834
835
836.. opcode:: BUILD_CONST_KEY_MAP (count)
837
838   The version of :opcode:`BUILD_MAP` specialized for constant keys.  *count*
839   values are consumed from the stack.  The top element on the stack contains
840   a tuple of keys.
841
842   .. versionadded:: 3.6
843
844
845.. opcode:: BUILD_STRING (count)
846
847   Concatenates *count* strings from the stack and pushes the resulting string
848   onto the stack.
849
850   .. versionadded:: 3.6
851
852
853.. opcode:: BUILD_TUPLE_UNPACK (count)
854
855   Pops *count* iterables from the stack, joins them in a single tuple,
856   and pushes the result.  Implements iterable unpacking in tuple
857   displays ``(*x, *y, *z)``.
858
859   .. versionadded:: 3.5
860
861
862.. opcode:: BUILD_TUPLE_UNPACK_WITH_CALL (count)
863
864   This is similar to :opcode:`BUILD_TUPLE_UNPACK`,
865   but is used for ``f(*x, *y, *z)`` call syntax. The stack item at position
866   ``count + 1`` should be the corresponding callable ``f``.
867
868   .. versionadded:: 3.6
869
870
871.. opcode:: BUILD_LIST_UNPACK (count)
872
873   This is similar to :opcode:`BUILD_TUPLE_UNPACK`, but pushes a list
874   instead of tuple.  Implements iterable unpacking in list
875   displays ``[*x, *y, *z]``.
876
877   .. versionadded:: 3.5
878
879
880.. opcode:: BUILD_SET_UNPACK (count)
881
882   This is similar to :opcode:`BUILD_TUPLE_UNPACK`, but pushes a set
883   instead of tuple.  Implements iterable unpacking in set
884   displays ``{*x, *y, *z}``.
885
886   .. versionadded:: 3.5
887
888
889.. opcode:: BUILD_MAP_UNPACK (count)
890
891   Pops *count* mappings from the stack, merges them into a single dictionary,
892   and pushes the result.  Implements dictionary unpacking in dictionary
893   displays ``{**x, **y, **z}``.
894
895   .. versionadded:: 3.5
896
897
898.. opcode:: BUILD_MAP_UNPACK_WITH_CALL (count)
899
900   This is similar to :opcode:`BUILD_MAP_UNPACK`,
901   but is used for ``f(**x, **y, **z)`` call syntax.  The stack item at
902   position ``count + 2`` should be the corresponding callable ``f``.
903
904   .. versionadded:: 3.5
905   .. versionchanged:: 3.6
906      The position of the callable is determined by adding 2 to the opcode
907      argument instead of encoding it in the second byte of the argument.
908
909
910.. opcode:: LOAD_ATTR (namei)
911
912   Replaces TOS with ``getattr(TOS, co_names[namei])``.
913
914
915.. opcode:: COMPARE_OP (opname)
916
917   Performs a Boolean operation.  The operation name can be found in
918   ``cmp_op[opname]``.
919
920
921.. opcode:: IMPORT_NAME (namei)
922
923   Imports the module ``co_names[namei]``.  TOS and TOS1 are popped and provide
924   the *fromlist* and *level* arguments of :func:`__import__`.  The module
925   object is pushed onto the stack.  The current namespace is not affected: for
926   a proper import statement, a subsequent :opcode:`STORE_FAST` instruction
927   modifies the namespace.
928
929
930.. opcode:: IMPORT_FROM (namei)
931
932   Loads the attribute ``co_names[namei]`` from the module found in TOS. The
933   resulting object is pushed onto the stack, to be subsequently stored by a
934   :opcode:`STORE_FAST` instruction.
935
936
937.. opcode:: JUMP_FORWARD (delta)
938
939   Increments bytecode counter by *delta*.
940
941
942.. opcode:: POP_JUMP_IF_TRUE (target)
943
944   If TOS is true, sets the bytecode counter to *target*.  TOS is popped.
945
946   .. versionadded:: 3.1
947
948
949.. opcode:: POP_JUMP_IF_FALSE (target)
950
951   If TOS is false, sets the bytecode counter to *target*.  TOS is popped.
952
953   .. versionadded:: 3.1
954
955
956.. opcode:: JUMP_IF_TRUE_OR_POP (target)
957
958   If TOS is true, sets the bytecode counter to *target* and leaves TOS on the
959   stack.  Otherwise (TOS is false), TOS is popped.
960
961   .. versionadded:: 3.1
962
963
964.. opcode:: JUMP_IF_FALSE_OR_POP (target)
965
966   If TOS is false, sets the bytecode counter to *target* and leaves TOS on the
967   stack.  Otherwise (TOS is true), TOS is popped.
968
969   .. versionadded:: 3.1
970
971
972.. opcode:: JUMP_ABSOLUTE (target)
973
974   Set bytecode counter to *target*.
975
976
977.. opcode:: FOR_ITER (delta)
978
979   TOS is an :term:`iterator`.  Call its :meth:`~iterator.__next__` method.  If
980   this yields a new value, push it on the stack (leaving the iterator below
981   it).  If the iterator indicates it is exhausted TOS is popped, and the byte
982   code counter is incremented by *delta*.
983
984
985.. opcode:: LOAD_GLOBAL (namei)
986
987   Loads the global named ``co_names[namei]`` onto the stack.
988
989
990.. opcode:: SETUP_LOOP (delta)
991
992   Pushes a block for a loop onto the block stack.  The block spans from the
993   current instruction with a size of *delta* bytes.
994
995
996.. opcode:: SETUP_EXCEPT (delta)
997
998   Pushes a try block from a try-except clause onto the block stack. *delta*
999   points to the first except block.
1000
1001
1002.. opcode:: SETUP_FINALLY (delta)
1003
1004   Pushes a try block from a try-except clause onto the block stack. *delta*
1005   points to the finally block.
1006
1007
1008.. opcode:: LOAD_FAST (var_num)
1009
1010   Pushes a reference to the local ``co_varnames[var_num]`` onto the stack.
1011
1012
1013.. opcode:: STORE_FAST (var_num)
1014
1015   Stores TOS into the local ``co_varnames[var_num]``.
1016
1017
1018.. opcode:: DELETE_FAST (var_num)
1019
1020   Deletes local ``co_varnames[var_num]``.
1021
1022
1023.. opcode:: LOAD_CLOSURE (i)
1024
1025   Pushes a reference to the cell contained in slot *i* of the cell and free
1026   variable storage.  The name of the variable is ``co_cellvars[i]`` if *i* is
1027   less than the length of *co_cellvars*.  Otherwise it is ``co_freevars[i -
1028   len(co_cellvars)]``.
1029
1030
1031.. opcode:: LOAD_DEREF (i)
1032
1033   Loads the cell contained in slot *i* of the cell and free variable storage.
1034   Pushes a reference to the object the cell contains on the stack.
1035
1036
1037.. opcode:: LOAD_CLASSDEREF (i)
1038
1039   Much like :opcode:`LOAD_DEREF` but first checks the locals dictionary before
1040   consulting the cell.  This is used for loading free variables in class
1041   bodies.
1042
1043   .. versionadded:: 3.4
1044
1045
1046.. opcode:: STORE_DEREF (i)
1047
1048   Stores TOS into the cell contained in slot *i* of the cell and free variable
1049   storage.
1050
1051
1052.. opcode:: DELETE_DEREF (i)
1053
1054   Empties the cell contained in slot *i* of the cell and free variable storage.
1055   Used by the :keyword:`del` statement.
1056
1057   .. versionadded:: 3.2
1058
1059
1060.. opcode:: RAISE_VARARGS (argc)
1061
1062   Raises an exception. *argc* indicates the number of arguments to the raise
1063   statement, ranging from 0 to 3.  The handler will find the traceback as TOS2,
1064   the parameter as TOS1, and the exception as TOS.
1065
1066
1067.. opcode:: CALL_FUNCTION (argc)
1068
1069   Calls a callable object with positional arguments.
1070   *argc* indicates the number of positional arguments.
1071   The top of the stack contains positional arguments, with the right-most
1072   argument on top.  Below the arguments is a callable object to call.
1073   ``CALL_FUNCTION`` pops all arguments and the callable object off the stack,
1074   calls the callable object with those arguments, and pushes the return value
1075   returned by the callable object.
1076
1077   .. versionchanged:: 3.6
1078      This opcode is used only for calls with positional arguments.
1079
1080
1081.. opcode:: CALL_FUNCTION_KW (argc)
1082
1083   Calls a callable object with positional (if any) and keyword arguments.
1084   *argc* indicates the total number of positional and keyword arguments.
1085   The top element on the stack contains a tuple of keyword argument names.
1086   Below that are keyword arguments in the order corresponding to the tuple.
1087   Below that are positional arguments, with the right-most parameter on
1088   top.  Below the arguments is a callable object to call.
1089   ``CALL_FUNCTION_KW`` pops all arguments and the callable object off the stack,
1090   calls the callable object with those arguments, and pushes the return value
1091   returned by the callable object.
1092
1093   .. versionchanged:: 3.6
1094      Keyword arguments are packed in a tuple instead of a dictionary,
1095      *argc* indicates the total number of arguments.
1096
1097
1098.. opcode:: CALL_FUNCTION_EX (flags)
1099
1100   Calls a callable object with variable set of positional and keyword
1101   arguments.  If the lowest bit of *flags* is set, the top of the stack
1102   contains a mapping object containing additional keyword arguments.
1103   Below that is an iterable object containing positional arguments and
1104   a callable object to call.  :opcode:`BUILD_MAP_UNPACK_WITH_CALL` and
1105   :opcode:`BUILD_TUPLE_UNPACK_WITH_CALL` can be used for merging multiple
1106   mapping objects and iterables containing arguments.
1107   Before the callable is called, the mapping object and iterable object
1108   are each "unpacked" and their contents passed in as keyword and
1109   positional arguments respectively.
1110   ``CALL_FUNCTION_EX`` pops all arguments and the callable object off the stack,
1111   calls the callable object with those arguments, and pushes the return value
1112   returned by the callable object.
1113
1114   .. versionadded:: 3.6
1115
1116
1117.. opcode:: LOAD_METHOD (namei)
1118
1119   Loads a method named ``co_names[namei]`` from TOS object. TOS is popped and
1120   method and TOS are pushed when interpreter can call unbound method directly.
1121   TOS will be used as the first argument (``self``) by :opcode:`CALL_METHOD`.
1122   Otherwise, ``NULL`` and  method is pushed (method is bound method or
1123   something else).
1124
1125   .. versionadded:: 3.7
1126
1127
1128.. opcode:: CALL_METHOD (argc)
1129
1130   Calls a method.  *argc* is number of positional arguments.
1131   Keyword arguments are not supported.  This opcode is designed to be used
1132   with :opcode:`LOAD_METHOD`.  Positional arguments are on top of the stack.
1133   Below them, two items described in :opcode:`LOAD_METHOD` on the stack.
1134   All of them are popped and return value is pushed.
1135
1136   .. versionadded:: 3.7
1137
1138
1139.. opcode:: MAKE_FUNCTION (argc)
1140
1141   Pushes a new function object on the stack.  From bottom to top, the consumed
1142   stack must consist of values if the argument carries a specified flag value
1143
1144   * ``0x01`` a tuple of default values for positional-only and
1145     positional-or-keyword parameters in positional order
1146   * ``0x02`` a dictionary of keyword-only parameters' default values
1147   * ``0x04`` an annotation dictionary
1148   * ``0x08`` a tuple containing cells for free variables, making a closure
1149   * the code associated with the function (at TOS1)
1150   * the :term:`qualified name` of the function (at TOS)
1151
1152
1153.. opcode:: BUILD_SLICE (argc)
1154
1155   .. index:: builtin: slice
1156
1157   Pushes a slice object on the stack.  *argc* must be 2 or 3.  If it is 2,
1158   ``slice(TOS1, TOS)`` is pushed; if it is 3, ``slice(TOS2, TOS1, TOS)`` is
1159   pushed. See the :func:`slice` built-in function for more information.
1160
1161
1162.. opcode:: EXTENDED_ARG (ext)
1163
1164   Prefixes any opcode which has an argument too big to fit into the default two
1165   bytes.  *ext* holds two additional bytes which, taken together with the
1166   subsequent opcode's argument, comprise a four-byte argument, *ext* being the
1167   two most-significant bytes.
1168
1169
1170.. opcode:: FORMAT_VALUE (flags)
1171
1172   Used for implementing formatted literal strings (f-strings).  Pops
1173   an optional *fmt_spec* from the stack, then a required *value*.
1174   *flags* is interpreted as follows:
1175
1176   * ``(flags & 0x03) == 0x00``: *value* is formatted as-is.
1177   * ``(flags & 0x03) == 0x01``: call :func:`str` on *value* before
1178     formatting it.
1179   * ``(flags & 0x03) == 0x02``: call :func:`repr` on *value* before
1180     formatting it.
1181   * ``(flags & 0x03) == 0x03``: call :func:`ascii` on *value* before
1182     formatting it.
1183   * ``(flags & 0x04) == 0x04``: pop *fmt_spec* from the stack and use
1184     it, else use an empty *fmt_spec*.
1185
1186   Formatting is performed using :c:func:`PyObject_Format`.  The
1187   result is pushed on the stack.
1188
1189   .. versionadded:: 3.6
1190
1191
1192.. opcode:: HAVE_ARGUMENT
1193
1194   This is not really an opcode.  It identifies the dividing line between
1195   opcodes which don't use their argument and those that do
1196   (``< HAVE_ARGUMENT`` and ``>= HAVE_ARGUMENT``, respectively).
1197
1198   .. versionchanged:: 3.6
1199      Now every instruction has an argument, but opcodes ``< HAVE_ARGUMENT``
1200      ignore it. Before, only opcodes ``>= HAVE_ARGUMENT`` had an argument.
1201
1202
1203.. _opcode_collections:
1204
1205Opcode collections
1206------------------
1207
1208These collections are provided for automatic introspection of bytecode
1209instructions:
1210
1211.. data:: opname
1212
1213   Sequence of operation names, indexable using the bytecode.
1214
1215
1216.. data:: opmap
1217
1218   Dictionary mapping operation names to bytecodes.
1219
1220
1221.. data:: cmp_op
1222
1223   Sequence of all compare operation names.
1224
1225
1226.. data:: hasconst
1227
1228   Sequence of bytecodes that access a constant.
1229
1230
1231.. data:: hasfree
1232
1233   Sequence of bytecodes that access a free variable (note that 'free' in this
1234   context refers to names in the current scope that are referenced by inner
1235   scopes or names in outer scopes that are referenced from this scope.  It does
1236   *not* include references to global or builtin scopes).
1237
1238
1239.. data:: hasname
1240
1241   Sequence of bytecodes that access an attribute by name.
1242
1243
1244.. data:: hasjrel
1245
1246   Sequence of bytecodes that have a relative jump target.
1247
1248
1249.. data:: hasjabs
1250
1251   Sequence of bytecodes that have an absolute jump target.
1252
1253
1254.. data:: haslocal
1255
1256   Sequence of bytecodes that access a local variable.
1257
1258
1259.. data:: hascompare
1260
1261   Sequence of bytecodes of Boolean operations.
1262