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