Debian Codegraph @

Doc/library/dis.rst

raw
1 :mod:`!dis` --- Disassembler for Python bytecode
2 ================================================
3
4 .. module:: dis
5 :synopsis: Disassembler for Python bytecode.
6
7 **Source code:** :source:`Lib/dis.py`
8
9 .. testsetup::
10
11 import dis
12 def myfunc(alist):
13 return len(alist)
14
15 --------------
16
17 The :mod:`dis` module supports the analysis of CPython :term:`bytecode` by
18 disassembling it. The CPython bytecode which this module takes as an input is
19 defined in the file :file:`Include/opcode.h` and used by the compiler and the
20 interpreter.
21
22 .. impl-detail::
23
24 Bytecode is an implementation detail of the CPython interpreter. No
25 guarantees are made that bytecode will not be added, removed, or changed
26 between versions of Python. Use of this module should not be considered to
27 work across Python VMs or Python releases.
28
29 .. versionchanged:: 3.6
30 Use 2 bytes for each instruction. Previously the number of bytes varied
31 by instruction.
32
33 .. versionchanged:: 3.10
34 The argument of jump, exception handling and loop instructions is now
35 the instruction offset rather than the byte offset.
36
37 .. versionchanged:: 3.11
38 Some instructions are accompanied by one or more inline cache entries,
39 which take the form of :opcode:`CACHE` instructions. These instructions
40 are hidden by default, but can be shown by passing ``show_caches=True`` to
41 any :mod:`dis` utility. Furthermore, the interpreter now adapts the
42 bytecode to specialize it for different runtime conditions. The
43 adaptive bytecode can be shown by passing ``adaptive=True``.
44
45 .. versionchanged:: 3.12
46 The argument of a jump is the offset of the target instruction relative
47 to the instruction that appears immediately after the jump instruction's
48 :opcode:`CACHE` entries.
49
50 As a consequence, the presence of the :opcode:`CACHE` instructions is
51 transparent for forward jumps but needs to be taken into account when
52 reasoning about backward jumps.
53
54 .. versionchanged:: 3.13
55 The output shows logical labels rather than instruction offsets
56 for jump targets and exception handlers. The ``-O`` command line
57 option and the ``show_offsets`` argument were added.
58
59 Example: Given the function :func:`!myfunc`::
60
61 def myfunc(alist):
62 return len(alist)
63
64 the following command can be used to display the disassembly of
65 :func:`!myfunc`:
66
67 .. doctest::
68
69 >>> dis.dis(myfunc)
70 2 RESUME 0
71 <BLANKLINE>
72 3 LOAD_GLOBAL 1 (len + NULL)
73 LOAD_FAST 0 (alist)
74 CALL 1
75 RETURN_VALUE
76
77 (The "2" is a line number).
78
79 .. _dis-cli:
80
81 Command-line interface
82 ----------------------
83
84 The :mod:`dis` module can be invoked as a script from the command line:
85
86 .. code-block:: sh
87
88 python -m dis [-h] [-C] [-O] [infile]
89
90 The following options are accepted:
91
92 .. program:: dis
93
94 .. option:: -h, --help
95
96 Display usage and exit.
97
98 .. option:: -C, --show-caches
99
100 Show inline caches.
101
102 .. versionadded:: 3.13
103
104 .. option:: -O, --show-offsets
105
106 Show offsets of instructions.
107
108 .. versionadded:: 3.13
109
110 If :file:`infile` is specified, its disassembled code will be written to stdout.
111 Otherwise, disassembly is performed on compiled source code received from stdin.
112
113 Bytecode analysis
114 -----------------
115
116 .. versionadded:: 3.4
117
118 The bytecode analysis API allows pieces of Python code to be wrapped in a
119 :class:`Bytecode` object that provides easy access to details of the compiled
120 code.
121
122 .. class:: Bytecode(x, *, first_line=None, current_offset=None,\
123 show_caches=False, adaptive=False, show_offsets=False)
124
125 Analyse the bytecode corresponding to a function, generator, asynchronous
126 generator, coroutine, method, string of source code, or a code object (as
127 returned by :func:`compile`).
128
129 This is a convenience wrapper around many of the functions listed below, most
130 notably :func:`get_instructions`, as iterating over a :class:`Bytecode`
131 instance yields the bytecode operations as :class:`Instruction` instances.
132
133 If *first_line* is not ``None``, it indicates the line number that should be
134 reported for the first source line in the disassembled code. Otherwise, the
135 source line information (if any) is taken directly from the disassembled code
136 object.
137
138 If *current_offset* is not ``None``, it refers to an instruction offset in the
139 disassembled code. Setting this means :meth:`.dis` will display a "current
140 instruction" marker against the specified opcode.
141
142 If *show_caches* is ``True``, :meth:`.dis` will display inline cache
143 entries used by the interpreter to specialize the bytecode.
144
145 If *adaptive* is ``True``, :meth:`.dis` will display specialized bytecode
146 that may be different from the original bytecode.
147
148 If *show_offsets* is ``True``, :meth:`.dis` will include instruction
149 offsets in the output.
150
151 .. classmethod:: from_traceback(tb, *, show_caches=False)
152
153 Construct a :class:`Bytecode` instance from the given traceback, setting
154 *current_offset* to the instruction responsible for the exception.
155
156 .. data:: codeobj
157
158 The compiled code object.
159
160 .. data:: first_line
161
162 The first source line of the code object (if available)
163
164 .. method:: dis()
165
166 Return a formatted view of the bytecode operations (the same as printed by
167 :func:`dis.dis`, but returned as a multi-line string).
168
169 .. method:: info()
170
171 Return a formatted multi-line string with detailed information about the
172 code object, like :func:`code_info`.
173
174 .. versionchanged:: 3.7
175 This can now handle coroutine and asynchronous generator objects.
176
177 .. versionchanged:: 3.11
178 Added the *show_caches* and *adaptive* parameters.
179
180 Example:
181
182 .. doctest::
183
184 >>> bytecode = dis.Bytecode(myfunc)
185 >>> for instr in bytecode:
186 ... print(instr.opname)
187 ...
188 RESUME
189 LOAD_GLOBAL
190 LOAD_FAST
191 CALL
192 RETURN_VALUE
193
194
195 Analysis functions
196 ------------------
197
198 The :mod:`dis` module also defines the following analysis functions that convert
199 the input directly to the desired output. They can be useful if only a single
200 operation is being performed, so the intermediate analysis object isn't useful:
201
202 .. function:: code_info(x)
203
204 Return a formatted multi-line string with detailed code object information
205 for the supplied function, generator, asynchronous generator, coroutine,
206 method, source code string or code object.
207
208 Note that the exact contents of code info strings are highly implementation
209 dependent and they may change arbitrarily across Python VMs or Python
210 releases.
211
212 .. versionadded:: 3.2
213
214 .. versionchanged:: 3.7
215 This can now handle coroutine and asynchronous generator objects.
216
217
218 .. function:: show_code(x, *, file=None)
219
220 Print detailed code object information for the supplied function, method,
221 source code string or code object to *file* (or ``sys.stdout`` if *file*
222 is not specified).
223
224 This is a convenient shorthand for ``print(code_info(x), file=file)``,
225 intended for interactive exploration at the interpreter prompt.
226
227 .. versionadded:: 3.2
228
229 .. versionchanged:: 3.4
230 Added *file* parameter.
231
232
233 .. function:: dis(x=None, *, file=None, depth=None, show_caches=False, adaptive=False)
234
235 Disassemble the *x* object. *x* can denote either a module, a class, a
236 method, a function, a generator, an asynchronous generator, a coroutine,
237 a code object, a string of source code or a byte sequence of raw bytecode.
238 For a module, it disassembles all functions. For a class, it disassembles
239 all methods (including class and static methods). For a code object or
240 sequence of raw bytecode, it prints one line per bytecode instruction.
241 It also recursively disassembles nested code objects. These can include
242 generator expressions, nested functions, the bodies of nested classes,
243 and the code objects used for :ref:`annotation scopes <annotation-scopes>`.
244 Strings are first compiled to code objects with the :func:`compile`
245 built-in function before being disassembled. If no object is provided, this
246 function disassembles the last traceback.
247
248 The disassembly is written as text to the supplied *file* argument if
249 provided and to ``sys.stdout`` otherwise.
250
251 The maximal depth of recursion is limited by *depth* unless it is ``None``.
252 ``depth=0`` means no recursion.
253
254 If *show_caches* is ``True``, this function will display inline cache
255 entries used by the interpreter to specialize the bytecode.
256
257 If *adaptive* is ``True``, this function will display specialized bytecode
258 that may be different from the original bytecode.
259
260 .. versionchanged:: 3.4
261 Added *file* parameter.
262
263 .. versionchanged:: 3.7
264 Implemented recursive disassembling and added *depth* parameter.
265
266 .. versionchanged:: 3.7
267 This can now handle coroutine and asynchronous generator objects.
268
269 .. versionchanged:: 3.11
270 Added the *show_caches* and *adaptive* parameters.
271
272
273 .. function:: distb(tb=None, *, file=None, show_caches=False, adaptive=False, \
274 show_offset=False)
275
276 Disassemble the top-of-stack function of a traceback, using the last
277 traceback if none was passed. The instruction causing the exception is
278 indicated.
279
280 The disassembly is written as text to the supplied *file* argument if
281 provided and to ``sys.stdout`` otherwise.
282
283 .. versionchanged:: 3.4
284 Added *file* parameter.
285
286 .. versionchanged:: 3.11
287 Added the *show_caches* and *adaptive* parameters.
288
289 .. versionchanged:: 3.13
290 Added the *show_offsets* parameter.
291
292 .. function:: disassemble(code, lasti=-1, *, file=None, show_caches=False, adaptive=False)
293 disco(code, lasti=-1, *, file=None, show_caches=False, adaptive=False,
294 show_offsets=False)
295
296 Disassemble a code object, indicating the last instruction if *lasti* was
297 provided. The output is divided in the following columns:
298
299 #. the line number, for the first instruction of each line
300 #. the current instruction, indicated as ``-->``,
301 #. a labelled instruction, indicated with ``>>``,
302 #. the address of the instruction,
303 #. the operation code name,
304 #. operation parameters, and
305 #. interpretation of the parameters in parentheses.
306
307 The parameter interpretation recognizes local and global variable names,
308 constant values, branch targets, and compare operators.
309
310 The disassembly is written as text to the supplied *file* argument if
311 provided and to ``sys.stdout`` otherwise.
312
313 .. versionchanged:: 3.4
314 Added *file* parameter.
315
316 .. versionchanged:: 3.11
317 Added the *show_caches* and *adaptive* parameters.
318
319 .. versionchanged:: 3.13
320 Added the *show_offsets* parameter.
321
322 .. function:: get_instructions(x, *, first_line=None, show_caches=False, adaptive=False)
323
324 Return an iterator over the instructions in the supplied function, method,
325 source code string or code object.
326
327 The iterator generates a series of :class:`Instruction` named tuples giving
328 the details of each operation in the supplied code.
329
330 If *first_line* is not ``None``, it indicates the line number that should be
331 reported for the first source line in the disassembled code. Otherwise, the
332 source line information (if any) is taken directly from the disassembled code
333 object.
334
335 The *adaptive* parameter works as it does in :func:`dis`.
336
337 .. versionadded:: 3.4
338
339 .. versionchanged:: 3.11
340 Added the *show_caches* and *adaptive* parameters.
341
342 .. versionchanged:: 3.13
343 The *show_caches* parameter is deprecated and has no effect. The iterator
344 generates the :class:`Instruction` instances with the *cache_info*
345 field populated (regardless of the value of *show_caches*) and it no longer
346 generates separate items for the cache entries.
347
348 .. function:: findlinestarts(code)
349
350 This generator function uses the :meth:`~codeobject.co_lines` method
351 of the :ref:`code object <code-objects>` *code* to find the offsets which
352 are starts of
353 lines in the source code. They are generated as ``(offset, lineno)`` pairs.
354
355 .. versionchanged:: 3.6
356 Line numbers can be decreasing. Before, they were always increasing.
357
358 .. versionchanged:: 3.10
359 The :pep:`626` :meth:`~codeobject.co_lines` method is used instead of the
360 :attr:`~codeobject.co_firstlineno` and :attr:`~codeobject.co_lnotab`
361 attributes of the :ref:`code object <code-objects>`.
362
363 .. versionchanged:: 3.13
364 Line numbers can be ``None`` for bytecode that does not map to source lines.
365
366
367 .. function:: findlabels(code)
368
369 Detect all offsets in the raw compiled bytecode string *code* which are jump targets, and
370 return a list of these offsets.
371
372
373 .. function:: stack_effect(opcode, oparg=None, *, jump=None)
374
375 Compute the stack effect of *opcode* with argument *oparg*.
376
377 If the code has a jump target and *jump* is ``True``, :func:`~stack_effect`
378 will return the stack effect of jumping. If *jump* is ``False``,
379 it will return the stack effect of not jumping. And if *jump* is
380 ``None`` (default), it will return the maximal stack effect of both cases.
381
382 .. versionadded:: 3.4
383
384 .. versionchanged:: 3.8
385 Added *jump* parameter.
386
387 .. versionchanged:: 3.13
388 If ``oparg`` is omitted (or ``None``), the stack effect is now returned
389 for ``oparg=0``. Previously this was an error for opcodes that use their
390 arg. It is also no longer an error to pass an integer ``oparg`` when
391 the ``opcode`` does not use it; the ``oparg`` in this case is ignored.
392
393
394 .. _bytecodes:
395
396 Python Bytecode Instructions
397 ----------------------------
398
399 The :func:`get_instructions` function and :class:`Bytecode` class provide
400 details of bytecode instructions as :class:`Instruction` instances:
401
402 .. class:: Instruction
403
404 Details for a bytecode operation
405
406 .. data:: opcode
407
408 numeric code for operation, corresponding to the opcode values listed
409 below and the bytecode values in the :ref:`opcode_collections`.
410
411
412 .. data:: opname
413
414 human readable name for operation
415
416
417 .. data:: baseopcode
418
419 numeric code for the base operation if operation is specialized;
420 otherwise equal to :data:`opcode`
421
422
423 .. data:: baseopname
424
425 human readable name for the base operation if operation is specialized;
426 otherwise equal to :data:`opname`
427
428
429 .. data:: arg
430
431 numeric argument to operation (if any), otherwise ``None``
432
433 .. data:: oparg
434
435 alias for :data:`arg`
436
437 .. data:: argval
438
439 resolved arg value (if any), otherwise ``None``
440
441
442 .. data:: argrepr
443
444 human readable description of operation argument (if any),
445 otherwise an empty string.
446
447
448 .. data:: offset
449
450 start index of operation within bytecode sequence
451
452
453 .. data:: start_offset
454
455 start index of operation within bytecode sequence, including prefixed
456 ``EXTENDED_ARG`` operations if present; otherwise equal to :data:`offset`
457
458
459 .. data:: cache_offset
460
461 start index of the cache entries following the operation
462
463
464 .. data:: end_offset
465
466 end index of the cache entries following the operation
467
468
469 .. data:: starts_line
470
471 ``True`` if this opcode starts a source line, otherwise ``False``
472
473
474 .. data:: line_number
475
476 source line number associated with this opcode (if any), otherwise ``None``
477
478
479 .. data:: is_jump_target
480
481 ``True`` if other code jumps to here, otherwise ``False``
482
483
484 .. data:: jump_target
485
486 bytecode index of the jump target if this is a jump operation,
487 otherwise ``None``
488
489
490 .. data:: positions
491
492 :class:`dis.Positions` object holding the
493 start and end locations that are covered by this instruction.
494
495 .. data:: cache_info
496
497 Information about the cache entries of this instruction, as
498 triplets of the form ``(name, size, data)``, where the ``name``
499 and ``size`` describe the cache format and data is the contents
500 of the cache. ``cache_info`` is ``None`` if the instruction does not have
501 caches.
502
503 .. versionadded:: 3.4
504
505 .. versionchanged:: 3.11
506
507 Field ``positions`` is added.
508
509 .. versionchanged:: 3.13
510
511 Changed field ``starts_line``.
512
513 Added fields ``start_offset``, ``cache_offset``, ``end_offset``,
514 ``baseopname``, ``baseopcode``, ``jump_target``, ``oparg``,
515 ``line_number`` and ``cache_info``.
516
517
518 .. class:: Positions
519
520 In case the information is not available, some fields might be ``None``.
521
522 .. data:: lineno
523 .. data:: end_lineno
524 .. data:: col_offset
525 .. data:: end_col_offset
526
527 .. versionadded:: 3.11
528
529
530 The Python compiler currently generates the following bytecode instructions.
531
532
533 **General instructions**
534
535 In the following, We will refer to the interpreter stack as ``STACK`` and describe
536 operations on it as if it was a Python list. The top of the stack corresponds to
537 ``STACK[-1]`` in this language.
538
539 .. opcode:: NOP
540
541 Do nothing code. Used as a placeholder by the bytecode optimizer, and to
542 generate line tracing events.
543
544
545 .. opcode:: POP_TOP
546
547 Removes the top-of-stack item::
548
549 STACK.pop()
550
551
552 .. opcode:: END_FOR
553
554 Removes the top-of-stack item.
555 Equivalent to ``POP_TOP``.
556 Used to clean up at the end of loops, hence the name.
557
558 .. versionadded:: 3.12
559
560
561 .. opcode:: END_SEND
562
563 Implements ``del STACK[-2]``.
564 Used to clean up when a generator exits.
565
566 .. versionadded:: 3.12
567
568
569 .. opcode:: COPY (i)
570
571 Push the i-th item to the top of the stack without removing it from its original
572 location::
573
574 assert i > 0
575 STACK.append(STACK[-i])
576
577 .. versionadded:: 3.11
578
579
580 .. opcode:: SWAP (i)
581
582 Swap the top of the stack with the i-th element::
583
584 STACK[-i], STACK[-1] = STACK[-1], STACK[-i]
585
586 .. versionadded:: 3.11
587
588
589 .. opcode:: CACHE
590
591 Rather than being an actual instruction, this opcode is used to mark extra
592 space for the interpreter to cache useful data directly in the bytecode
593 itself. It is automatically hidden by all ``dis`` utilities, but can be
594 viewed with ``show_caches=True``.
595
596 Logically, this space is part of the preceding instruction. Many opcodes
597 expect to be followed by an exact number of caches, and will instruct the
598 interpreter to skip over them at runtime.
599
600 Populated caches can look like arbitrary instructions, so great care should
601 be taken when reading or modifying raw, adaptive bytecode containing
602 quickened data.
603
604 .. versionadded:: 3.11
605
606
607 **Unary operations**
608
609 Unary operations take the top of the stack, apply the operation, and push the
610 result back on the stack.
611
612
613 .. opcode:: UNARY_NEGATIVE
614
615 Implements ``STACK[-1] = -STACK[-1]``.
616
617
618 .. opcode:: UNARY_NOT
619
620 Implements ``STACK[-1] = not STACK[-1]``.
621
622 .. versionchanged:: 3.13
623 This instruction now requires an exact :class:`bool` operand.
624
625
626 .. opcode:: UNARY_INVERT
627
628 Implements ``STACK[-1] = ~STACK[-1]``.
629
630
631 .. opcode:: GET_ITER
632
633 Implements ``STACK[-1] = iter(STACK[-1])``.
634
635
636 .. opcode:: GET_YIELD_FROM_ITER
637
638 If ``STACK[-1]`` is a :term:`generator iterator` or :term:`coroutine` object
639 it is left as is. Otherwise, implements ``STACK[-1] = iter(STACK[-1])``.
640
641 .. versionadded:: 3.5
642
643
644 .. opcode:: TO_BOOL
645
646 Implements ``STACK[-1] = bool(STACK[-1])``.
647
648 .. versionadded:: 3.13
649
650
651 **Binary and in-place operations**
652
653 Binary operations remove the top two items from the stack (``STACK[-1]`` and
654 ``STACK[-2]``). They perform the operation, then put the result back on the stack.
655
656 In-place operations are like binary operations, but the operation is done in-place
657 when ``STACK[-2]`` supports it, and the resulting ``STACK[-1]`` may be (but does
658 not have to be) the original ``STACK[-2]``.
659
660
661 .. opcode:: BINARY_OP (op)
662
663 Implements the binary and in-place operators (depending on the value of
664 *op*)::
665
666 rhs = STACK.pop()
667 lhs = STACK.pop()
668 STACK.append(lhs op rhs)
669
670 .. versionadded:: 3.11
671
672
673 .. opcode:: BINARY_SUBSCR
674
675 Implements::
676
677 key = STACK.pop()
678 container = STACK.pop()
679 STACK.append(container[key])
680
681
682 .. opcode:: STORE_SUBSCR
683
684 Implements::
685
686 key = STACK.pop()
687 container = STACK.pop()
688 value = STACK.pop()
689 container[key] = value
690
691
692 .. opcode:: DELETE_SUBSCR
693
694 Implements::
695
696 key = STACK.pop()
697 container = STACK.pop()
698 del container[key]
699
700 .. opcode:: BINARY_SLICE
701
702 Implements::
703
704 end = STACK.pop()
705 start = STACK.pop()
706 container = STACK.pop()
707 STACK.append(container[start:end])
708
709 .. versionadded:: 3.12
710
711
712 .. opcode:: STORE_SLICE
713
714 Implements::
715
716 end = STACK.pop()
717 start = STACK.pop()
718 container = STACK.pop()
719 value = STACK.pop()
720 container[start:end] = value
721
722 .. versionadded:: 3.12
723
724
725 **Coroutine opcodes**
726
727 .. opcode:: GET_AWAITABLE (where)
728
729 Implements ``STACK[-1] = get_awaitable(STACK[-1])``, where ``get_awaitable(o)``
730 returns ``o`` if ``o`` is a coroutine object or a generator object with
731 the :data:`~inspect.CO_ITERABLE_COROUTINE` flag, or resolves
732 ``o.__await__``.
733
734 If the ``where`` operand is nonzero, it indicates where the instruction
735 occurs:
736
737 * ``1``: After a call to ``__aenter__``
738 * ``2``: After a call to ``__aexit__``
739
740 .. versionadded:: 3.5
741
742 .. versionchanged:: 3.11
743 Previously, this instruction did not have an oparg.
744
745
746 .. opcode:: GET_AITER
747
748 Implements ``STACK[-1] = STACK[-1].__aiter__()``.
749
750 .. versionadded:: 3.5
751 .. versionchanged:: 3.7
752 Returning awaitable objects from ``__aiter__`` is no longer
753 supported.
754
755
756 .. opcode:: GET_ANEXT
757
758 Implement ``STACK.append(get_awaitable(STACK[-1].__anext__()))`` to the stack.
759 See ``GET_AWAITABLE`` for details about ``get_awaitable``.
760
761 .. versionadded:: 3.5
762
763
764 .. opcode:: END_ASYNC_FOR
765
766 Terminates an :keyword:`async for` loop. Handles an exception raised
767 when awaiting a next item. The stack contains the async iterable in
768 ``STACK[-2]`` and the raised exception in ``STACK[-1]``. Both are popped.
769 If the exception is not :exc:`StopAsyncIteration`, it is re-raised.
770
771 .. versionadded:: 3.8
772
773 .. versionchanged:: 3.11
774 Exception representation on the stack now consist of one, not three, items.
775
776
777 .. opcode:: CLEANUP_THROW
778
779 Handles an exception raised during a :meth:`~generator.throw` or
780 :meth:`~generator.close` call through the current frame. If ``STACK[-1]`` is an
781 instance of :exc:`StopIteration`, pop three values from the stack and push
782 its ``value`` member. Otherwise, re-raise ``STACK[-1]``.
783
784 .. versionadded:: 3.12
785
786
787 .. opcode:: BEFORE_ASYNC_WITH
788
789 Resolves ``__aenter__`` and ``__aexit__`` from ``STACK[-1]``.
790 Pushes ``__aexit__`` and result of ``__aenter__()`` to the stack::
791
792 STACK.extend((__aexit__, __aenter__())
793
794 .. versionadded:: 3.5
795
796
797
798 **Miscellaneous opcodes**
799
800 .. opcode:: SET_ADD (i)
801
802 Implements::
803
804 item = STACK.pop()
805 set.add(STACK[-i], item)
806
807 Used to implement set comprehensions.
808
809
810 .. opcode:: LIST_APPEND (i)
811
812 Implements::
813
814 item = STACK.pop()
815 list.append(STACK[-i], item)
816
817 Used to implement list comprehensions.
818
819
820 .. opcode:: MAP_ADD (i)
821
822 Implements::
823
824 value = STACK.pop()
825 key = STACK.pop()
826 dict.__setitem__(STACK[-i], key, value)
827
828 Used to implement dict comprehensions.
829
830 .. versionadded:: 3.1
831 .. versionchanged:: 3.8
832 Map value is ``STACK[-1]`` and map key is ``STACK[-2]``. Before, those
833 were reversed.
834
835 For all of the :opcode:`SET_ADD`, :opcode:`LIST_APPEND` and :opcode:`MAP_ADD`
836 instructions, while the added value or key/value pair is popped off, the
837 container object remains on the stack so that it is available for further
838 iterations of the loop.
839
840
841 .. opcode:: RETURN_VALUE
842
843 Returns with ``STACK[-1]`` to the caller of the function.
844
845
846 .. opcode:: RETURN_CONST (consti)
847
848 Returns with ``co_consts[consti]`` to the caller of the function.
849
850 .. versionadded:: 3.12
851
852
853 .. opcode:: YIELD_VALUE
854
855 Yields ``STACK.pop()`` from a :term:`generator`.
856
857 .. versionchanged:: 3.11
858 oparg set to be the stack depth.
859
860 .. versionchanged:: 3.12
861 oparg set to be the exception block depth, for efficient closing of generators.
862
863 .. versionchanged:: 3.13
864 oparg is ``1`` if this instruction is part of a yield-from or await, and ``0``
865 otherwise.
866
867 .. opcode:: SETUP_ANNOTATIONS
868
869 Checks whether ``__annotations__`` is defined in ``locals()``, if not it is
870 set up to an empty ``dict``. This opcode is only emitted if a class
871 or module body contains :term:`variable annotations <variable annotation>`
872 statically.
873
874 .. versionadded:: 3.6
875
876
877 .. opcode:: POP_EXCEPT
878
879 Pops a value from the stack, which is used to restore the exception state.
880
881 .. versionchanged:: 3.11
882 Exception representation on the stack now consist of one, not three, items.
883
884 .. opcode:: RERAISE
885
886 Re-raises the exception currently on top of the stack. If oparg is non-zero,
887 pops an additional value from the stack which is used to set
888 :attr:`~frame.f_lasti` of the current frame.
889
890 .. versionadded:: 3.9
891
892 .. versionchanged:: 3.11
893 Exception representation on the stack now consist of one, not three, items.
894
895 .. opcode:: PUSH_EXC_INFO
896
897 Pops a value from the stack. Pushes the current exception to the top of the stack.
898 Pushes the value originally popped back to the stack.
899 Used in exception handlers.
900
901 .. versionadded:: 3.11
902
903 .. opcode:: CHECK_EXC_MATCH
904
905 Performs exception matching for ``except``. Tests whether the ``STACK[-2]``
906 is an exception matching ``STACK[-1]``. Pops ``STACK[-1]`` and pushes the boolean
907 result of the test.
908
909 .. versionadded:: 3.11
910
911 .. opcode:: CHECK_EG_MATCH
912
913 Performs exception matching for ``except*``. Applies ``split(STACK[-1])`` on
914 the exception group representing ``STACK[-2]``.
915
916 In case of a match, pops two items from the stack and pushes the
917 non-matching subgroup (``None`` in case of full match) followed by the
918 matching subgroup. When there is no match, pops one item (the match
919 type) and pushes ``None``.
920
921 .. versionadded:: 3.11
922
923 .. opcode:: WITH_EXCEPT_START
924
925 Calls the function in position 4 on the stack with arguments (type, val, tb)
926 representing the exception at the top of the stack.
927 Used to implement the call ``context_manager.__exit__(*exc_info())`` when an exception
928 has occurred in a :keyword:`with` statement.
929
930 .. versionadded:: 3.9
931
932 .. versionchanged:: 3.11
933 The ``__exit__`` function is in position 4 of the stack rather than 7.
934 Exception representation on the stack now consist of one, not three, items.
935
936
937 .. opcode:: LOAD_ASSERTION_ERROR
938
939 Pushes :exc:`AssertionError` onto the stack. Used by the :keyword:`assert`
940 statement.
941
942 .. versionadded:: 3.9
943
944
945 .. opcode:: LOAD_BUILD_CLASS
946
947 Pushes :func:`!builtins.__build_class__` onto the stack. It is later called
948 to construct a class.
949
950
951 .. opcode:: BEFORE_WITH
952
953 This opcode performs several operations before a with block starts. First,
954 it loads :meth:`~object.__exit__` from the context manager and pushes it onto
955 the stack for later use by :opcode:`WITH_EXCEPT_START`. Then,
956 :meth:`~object.__enter__` is called. Finally, the result of calling the
957 ``__enter__()`` method is pushed onto the stack.
958
959 .. versionadded:: 3.11
960
961
962 .. opcode:: GET_LEN
963
964 Perform ``STACK.append(len(STACK[-1]))``. Used in :keyword:`match` statements where
965 comparison with structure of pattern is needed.
966
967 .. versionadded:: 3.10
968
969
970 .. opcode:: MATCH_MAPPING
971
972 If ``STACK[-1]`` is an instance of :class:`collections.abc.Mapping` (or, more
973 technically: if it has the :c:macro:`Py_TPFLAGS_MAPPING` flag set in its
974 :c:member:`~PyTypeObject.tp_flags`), push ``True`` onto the stack. Otherwise,
975 push ``False``.
976
977 .. versionadded:: 3.10
978
979
980 .. opcode:: MATCH_SEQUENCE
981
982 If ``STACK[-1]`` is an instance of :class:`collections.abc.Sequence` and is *not* an instance
983 of :class:`str`/:class:`bytes`/:class:`bytearray` (or, more technically: if it has
984 the :c:macro:`Py_TPFLAGS_SEQUENCE` flag set in its :c:member:`~PyTypeObject.tp_flags`),
985 push ``True`` onto the stack. Otherwise, push ``False``.
986
987 .. versionadded:: 3.10
988
989
990 .. opcode:: MATCH_KEYS
991
992 ``STACK[-1]`` is a tuple of mapping keys, and ``STACK[-2]`` is the match subject.
993 If ``STACK[-2]`` contains all of the keys in ``STACK[-1]``, push a :class:`tuple`
994 containing the corresponding values. Otherwise, push ``None``.
995
996 .. versionadded:: 3.10
997
998 .. versionchanged:: 3.11
999 Previously, this instruction also pushed a boolean value indicating
1000 success (``True``) or failure (``False``).
1001
1002
1003 .. opcode:: STORE_NAME (namei)
1004
1005 Implements ``name = STACK.pop()``. *namei* is the index of *name* in the attribute
1006 :attr:`~codeobject.co_names` of the :ref:`code object <code-objects>`.
1007 The compiler tries to use :opcode:`STORE_FAST` or :opcode:`STORE_GLOBAL` if possible.
1008
1009
1010 .. opcode:: DELETE_NAME (namei)
1011
1012 Implements ``del name``, where *namei* is the index into :attr:`~codeobject.co_names`
1013 attribute of the :ref:`code object <code-objects>`.
1014
1015
1016 .. opcode:: UNPACK_SEQUENCE (count)
1017
1018 Unpacks ``STACK[-1]`` into *count* individual values, which are put onto the stack
1019 right-to-left. Require there to be exactly *count* values.::
1020
1021 assert(len(STACK[-1]) == count)
1022 STACK.extend(STACK.pop()[:-count-1:-1])
1023
1024
1025 .. opcode:: UNPACK_EX (counts)
1026
1027 Implements assignment with a starred target: Unpacks an iterable in ``STACK[-1]``
1028 into individual values, where the total number of values can be smaller than the
1029 number of items in the iterable: one of the new values will be a list of all
1030 leftover items.
1031
1032 The number of values before and after the list value is limited to 255.
1033
1034 The number of values before the list value is encoded in the argument of the
1035 opcode. The number of values after the list if any is encoded using an
1036 ``EXTENDED_ARG``. As a consequence, the argument can be seen as a two bytes values
1037 where the low byte of *counts* is the number of values before the list value, the
1038 high byte of *counts* the number of values after it.
1039
1040 The extracted values are put onto the stack right-to-left, i.e. ``a, *b, c = d``
1041 will be stored after execution as ``STACK.extend((a, b, c))``.
1042
1043
1044 .. opcode:: STORE_ATTR (namei)
1045
1046 Implements::
1047
1048 obj = STACK.pop()
1049 value = STACK.pop()
1050 obj.name = value
1051
1052 where *namei* is the index of name in :attr:`~codeobject.co_names` of the
1053 :ref:`code object <code-objects>`.
1054
1055 .. opcode:: DELETE_ATTR (namei)
1056
1057 Implements::
1058
1059 obj = STACK.pop()
1060 del obj.name
1061
1062 where *namei* is the index of name into :attr:`~codeobject.co_names` of the
1063 :ref:`code object <code-objects>`.
1064
1065
1066 .. opcode:: STORE_GLOBAL (namei)
1067
1068 Works as :opcode:`STORE_NAME`, but stores the name as a global.
1069
1070
1071 .. opcode:: DELETE_GLOBAL (namei)
1072
1073 Works as :opcode:`DELETE_NAME`, but deletes a global name.
1074
1075
1076 .. opcode:: LOAD_CONST (consti)
1077
1078 Pushes ``co_consts[consti]`` onto the stack.
1079
1080
1081 .. opcode:: LOAD_NAME (namei)
1082
1083 Pushes the value associated with ``co_names[namei]`` onto the stack.
1084 The name is looked up within the locals, then the globals, then the builtins.
1085
1086
1087 .. opcode:: LOAD_LOCALS
1088
1089 Pushes a reference to the locals dictionary onto the stack. This is used
1090 to prepare namespace dictionaries for :opcode:`LOAD_FROM_DICT_OR_DEREF`
1091 and :opcode:`LOAD_FROM_DICT_OR_GLOBALS`.
1092
1093 .. versionadded:: 3.12
1094
1095
1096 .. opcode:: LOAD_FROM_DICT_OR_GLOBALS (i)
1097
1098 Pops a mapping off the stack and looks up the value for ``co_names[namei]``.
1099 If the name is not found there, looks it up in the globals and then the builtins,
1100 similar to :opcode:`LOAD_GLOBAL`.
1101 This is used for loading global variables in
1102 :ref:`annotation scopes <annotation-scopes>` within class bodies.
1103
1104 .. versionadded:: 3.12
1105
1106
1107 .. opcode:: BUILD_TUPLE (count)
1108
1109 Creates a tuple consuming *count* items from the stack, and pushes the
1110 resulting tuple onto the stack::
1111
1112 if count == 0:
1113 value = ()
1114 else:
1115 value = tuple(STACK[-count:])
1116 STACK = STACK[:-count]
1117
1118 STACK.append(value)
1119
1120
1121 .. opcode:: BUILD_LIST (count)
1122
1123 Works as :opcode:`BUILD_TUPLE`, but creates a list.
1124
1125
1126 .. opcode:: BUILD_SET (count)
1127
1128 Works as :opcode:`BUILD_TUPLE`, but creates a set.
1129
1130
1131 .. opcode:: BUILD_MAP (count)
1132
1133 Pushes a new dictionary object onto the stack. Pops ``2 * count`` items
1134 so that the dictionary holds *count* entries:
1135 ``{..., STACK[-4]: STACK[-3], STACK[-2]: STACK[-1]}``.
1136
1137 .. versionchanged:: 3.5
1138 The dictionary is created from stack items instead of creating an
1139 empty dictionary pre-sized to hold *count* items.
1140
1141
1142 .. opcode:: BUILD_CONST_KEY_MAP (count)
1143
1144 The version of :opcode:`BUILD_MAP` specialized for constant keys. Pops the
1145 top element on the stack which contains a tuple of keys, then starting from
1146 ``STACK[-2]``, pops *count* values to form values in the built dictionary.
1147
1148 .. versionadded:: 3.6
1149
1150
1151 .. opcode:: BUILD_STRING (count)
1152
1153 Concatenates *count* strings from the stack and pushes the resulting string
1154 onto the stack.
1155
1156 .. versionadded:: 3.6
1157
1158
1159 .. opcode:: LIST_EXTEND (i)
1160
1161 Implements::
1162
1163 seq = STACK.pop()
1164 list.extend(STACK[-i], seq)
1165
1166 Used to build lists.
1167
1168 .. versionadded:: 3.9
1169
1170
1171 .. opcode:: SET_UPDATE (i)
1172
1173 Implements::
1174
1175 seq = STACK.pop()
1176 set.update(STACK[-i], seq)
1177
1178 Used to build sets.
1179
1180 .. versionadded:: 3.9
1181
1182
1183 .. opcode:: DICT_UPDATE (i)
1184
1185 Implements::
1186
1187 map = STACK.pop()
1188 dict.update(STACK[-i], map)
1189
1190 Used to build dicts.
1191
1192 .. versionadded:: 3.9
1193
1194
1195 .. opcode:: DICT_MERGE (i)
1196
1197 Like :opcode:`DICT_UPDATE` but raises an exception for duplicate keys.
1198
1199 .. versionadded:: 3.9
1200
1201
1202 .. opcode:: LOAD_ATTR (namei)
1203
1204 If the low bit of ``namei`` is not set, this replaces ``STACK[-1]`` with
1205 ``getattr(STACK[-1], co_names[namei>>1])``.
1206
1207 If the low bit of ``namei`` is set, this will attempt to load a method named
1208 ``co_names[namei>>1]`` from the ``STACK[-1]`` object. ``STACK[-1]`` is popped.
1209 This bytecode distinguishes two cases: if ``STACK[-1]`` has a method with the
1210 correct name, the bytecode pushes the unbound method and ``STACK[-1]``.
1211 ``STACK[-1]`` will be used as the first argument (``self``) by :opcode:`CALL`
1212 or :opcode:`CALL_KW` when calling the unbound method.
1213 Otherwise, ``NULL`` and the object returned by
1214 the attribute lookup are pushed.
1215
1216 .. versionchanged:: 3.12
1217 If the low bit of ``namei`` is set, then a ``NULL`` or ``self`` is
1218 pushed to the stack before the attribute or unbound method respectively.
1219
1220
1221 .. opcode:: LOAD_SUPER_ATTR (namei)
1222
1223 This opcode implements :func:`super`, both in its zero-argument and
1224 two-argument forms (e.g. ``super().method()``, ``super().attr`` and
1225 ``super(cls, self).method()``, ``super(cls, self).attr``).
1226
1227 It pops three values from the stack (from top of stack down):
1228
1229 * ``self``: the first argument to the current method
1230 * ``cls``: the class within which the current method was defined
1231 * the global ``super``
1232
1233 With respect to its argument, it works similarly to :opcode:`LOAD_ATTR`,
1234 except that ``namei`` is shifted left by 2 bits instead of 1.
1235
1236 The low bit of ``namei`` signals to attempt a method load, as with
1237 :opcode:`LOAD_ATTR`, which results in pushing ``NULL`` and the loaded method.
1238 When it is unset a single value is pushed to the stack.
1239
1240 The second-low bit of ``namei``, if set, means that this was a two-argument
1241 call to :func:`super` (unset means zero-argument).
1242
1243 .. versionadded:: 3.12
1244
1245
1246 .. opcode:: COMPARE_OP (opname)
1247
1248 Performs a Boolean operation. The operation name can be found in
1249 ``cmp_op[opname >> 5]``. If the fifth-lowest bit of ``opname`` is set
1250 (``opname & 16``), the result should be coerced to ``bool``.
1251
1252 .. versionchanged:: 3.13
1253 The fifth-lowest bit of the oparg now indicates a forced conversion to
1254 :class:`bool`.
1255
1256
1257 .. opcode:: IS_OP (invert)
1258
1259 Performs ``is`` comparison, or ``is not`` if ``invert`` is 1.
1260
1261 .. versionadded:: 3.9
1262
1263
1264 .. opcode:: CONTAINS_OP (invert)
1265
1266 Performs ``in`` comparison, or ``not in`` if ``invert`` is 1.
1267
1268 .. versionadded:: 3.9
1269
1270
1271 .. opcode:: IMPORT_NAME (namei)
1272
1273 Imports the module ``co_names[namei]``. ``STACK[-1]`` and ``STACK[-2]`` are
1274 popped and provide the *fromlist* and *level* arguments of :func:`__import__`.
1275 The module object is pushed onto the stack. The current namespace is not affected: for a proper import statement, a subsequent :opcode:`STORE_FAST` instruction
1276 modifies the namespace.
1277
1278
1279 .. opcode:: IMPORT_FROM (namei)
1280
1281 Loads the attribute ``co_names[namei]`` from the module found in ``STACK[-1]``.
1282 The resulting object is pushed onto the stack, to be subsequently stored by a
1283 :opcode:`STORE_FAST` instruction.
1284
1285
1286 .. opcode:: JUMP_FORWARD (delta)
1287
1288 Increments bytecode counter by *delta*.
1289
1290
1291 .. opcode:: JUMP_BACKWARD (delta)
1292
1293 Decrements bytecode counter by *delta*. Checks for interrupts.
1294
1295 .. versionadded:: 3.11
1296
1297
1298 .. opcode:: JUMP_BACKWARD_NO_INTERRUPT (delta)
1299
1300 Decrements bytecode counter by *delta*. Does not check for interrupts.
1301
1302 .. versionadded:: 3.11
1303
1304
1305 .. opcode:: POP_JUMP_IF_TRUE (delta)
1306
1307 If ``STACK[-1]`` is true, increments the bytecode counter by *delta*.
1308 ``STACK[-1]`` is popped.
1309
1310 .. versionchanged:: 3.11
1311 The oparg is now a relative delta rather than an absolute target.
1312 This opcode is a pseudo-instruction, replaced in final bytecode by
1313 the directed versions (forward/backward).
1314
1315 .. versionchanged:: 3.12
1316 This is no longer a pseudo-instruction.
1317
1318 .. versionchanged:: 3.13
1319 This instruction now requires an exact :class:`bool` operand.
1320
1321 .. opcode:: POP_JUMP_IF_FALSE (delta)
1322
1323 If ``STACK[-1]`` is false, increments the bytecode counter by *delta*.
1324 ``STACK[-1]`` is popped.
1325
1326 .. versionchanged:: 3.11
1327 The oparg is now a relative delta rather than an absolute target.
1328 This opcode is a pseudo-instruction, replaced in final bytecode by
1329 the directed versions (forward/backward).
1330
1331 .. versionchanged:: 3.12
1332 This is no longer a pseudo-instruction.
1333
1334 .. versionchanged:: 3.13
1335 This instruction now requires an exact :class:`bool` operand.
1336
1337 .. opcode:: POP_JUMP_IF_NOT_NONE (delta)
1338
1339 If ``STACK[-1]`` is not ``None``, increments the bytecode counter by *delta*.
1340 ``STACK[-1]`` is popped.
1341
1342 .. versionadded:: 3.11
1343
1344 .. versionchanged:: 3.12
1345 This is no longer a pseudo-instruction.
1346
1347
1348 .. opcode:: POP_JUMP_IF_NONE (delta)
1349
1350 If ``STACK[-1]`` is ``None``, increments the bytecode counter by *delta*.
1351 ``STACK[-1]`` is popped.
1352
1353 .. versionadded:: 3.11
1354
1355 .. versionchanged:: 3.12
1356 This is no longer a pseudo-instruction.
1357
1358 .. opcode:: FOR_ITER (delta)
1359
1360 ``STACK[-1]`` is an :term:`iterator`. Call its :meth:`~iterator.__next__` method.
1361 If this yields a new value, push it on the stack (leaving the iterator below
1362 it). If the iterator indicates it is exhausted then the byte code counter is
1363 incremented by *delta*.
1364
1365 .. versionchanged:: 3.12
1366 Up until 3.11 the iterator was popped when it was exhausted.
1367
1368 .. opcode:: LOAD_GLOBAL (namei)
1369
1370 Loads the global named ``co_names[namei>>1]`` onto the stack.
1371
1372 .. versionchanged:: 3.11
1373 If the low bit of ``namei`` is set, then a ``NULL`` is pushed to the
1374 stack before the global variable.
1375
1376 .. opcode:: LOAD_FAST (var_num)
1377
1378 Pushes a reference to the local ``co_varnames[var_num]`` onto the stack.
1379
1380 .. versionchanged:: 3.12
1381 This opcode is now only used in situations where the local variable is
1382 guaranteed to be initialized. It cannot raise :exc:`UnboundLocalError`.
1383
1384 .. opcode:: LOAD_FAST_LOAD_FAST (var_nums)
1385
1386 Pushes references to ``co_varnames[var_nums >> 4]`` and
1387 ``co_varnames[var_nums & 15]`` onto the stack.
1388
1389 .. versionadded:: 3.13
1390
1391 .. opcode:: LOAD_FAST_CHECK (var_num)
1392
1393 Pushes a reference to the local ``co_varnames[var_num]`` onto the stack,
1394 raising an :exc:`UnboundLocalError` if the local variable has not been
1395 initialized.
1396
1397 .. versionadded:: 3.12
1398
1399 .. opcode:: LOAD_FAST_AND_CLEAR (var_num)
1400
1401 Pushes a reference to the local ``co_varnames[var_num]`` onto the stack (or
1402 pushes ``NULL`` onto the stack if the local variable has not been
1403 initialized) and sets ``co_varnames[var_num]`` to ``NULL``.
1404
1405 .. versionadded:: 3.12
1406
1407 .. opcode:: STORE_FAST (var_num)
1408
1409 Stores ``STACK.pop()`` into the local ``co_varnames[var_num]``.
1410
1411 .. opcode:: STORE_FAST_STORE_FAST (var_nums)
1412
1413 Stores ``STACK[-1]`` into ``co_varnames[var_nums >> 4]``
1414 and ``STACK[-2]`` into ``co_varnames[var_nums & 15]``.
1415
1416 .. versionadded:: 3.13
1417
1418 .. opcode:: STORE_FAST_LOAD_FAST (var_nums)
1419
1420 Stores ``STACK.pop()`` into the local ``co_varnames[var_nums >> 4]``
1421 and pushes a reference to the local ``co_varnames[var_nums & 15]``
1422 onto the stack.
1423
1424 .. versionadded:: 3.13
1425
1426 .. opcode:: DELETE_FAST (var_num)
1427
1428 Deletes local ``co_varnames[var_num]``.
1429
1430
1431 .. opcode:: MAKE_CELL (i)
1432
1433 Creates a new cell in slot ``i``. If that slot is nonempty then
1434 that value is stored into the new cell.
1435
1436 .. versionadded:: 3.11
1437
1438
1439 .. opcode:: LOAD_DEREF (i)
1440
1441 Loads the cell contained in slot ``i`` of the "fast locals" storage.
1442 Pushes a reference to the object the cell contains on the stack.
1443
1444 .. versionchanged:: 3.11
1445 ``i`` is no longer offset by the length of :attr:`~codeobject.co_varnames`.
1446
1447
1448 .. opcode:: LOAD_FROM_DICT_OR_DEREF (i)
1449
1450 Pops a mapping off the stack and looks up the name associated with
1451 slot ``i`` of the "fast locals" storage in this mapping.
1452 If the name is not found there, loads it from the cell contained in
1453 slot ``i``, similar to :opcode:`LOAD_DEREF`. This is used for loading
1454 :term:`closure variables <closure variable>` in class bodies (which previously used
1455 :opcode:`!LOAD_CLASSDEREF`) and in
1456 :ref:`annotation scopes <annotation-scopes>` within class bodies.
1457
1458 .. versionadded:: 3.12
1459
1460
1461 .. opcode:: STORE_DEREF (i)
1462
1463 Stores ``STACK.pop()`` into the cell contained in slot ``i`` of the "fast locals"
1464 storage.
1465
1466 .. versionchanged:: 3.11
1467 ``i`` is no longer offset by the length of :attr:`~codeobject.co_varnames`.
1468
1469
1470 .. opcode:: DELETE_DEREF (i)
1471
1472 Empties the cell contained in slot ``i`` of the "fast locals" storage.
1473 Used by the :keyword:`del` statement.
1474
1475 .. versionadded:: 3.2
1476
1477 .. versionchanged:: 3.11
1478 ``i`` is no longer offset by the length of :attr:`~codeobject.co_varnames`.
1479
1480
1481 .. opcode:: COPY_FREE_VARS (n)
1482
1483 Copies the ``n`` :term:`free (closure) variables <closure variable>` from the closure
1484 into the frame. Removes the need for special code on the caller's side when calling
1485 closures.
1486
1487 .. versionadded:: 3.11
1488
1489
1490 .. opcode:: RAISE_VARARGS (argc)
1491
1492 Raises an exception using one of the 3 forms of the ``raise`` statement,
1493 depending on the value of *argc*:
1494
1495 * 0: ``raise`` (re-raise previous exception)
1496 * 1: ``raise STACK[-1]`` (raise exception instance or type at ``STACK[-1]``)
1497 * 2: ``raise STACK[-2] from STACK[-1]`` (raise exception instance or type at
1498 ``STACK[-2]`` with ``__cause__`` set to ``STACK[-1]``)
1499
1500
1501 .. opcode:: CALL (argc)
1502
1503 Calls a callable object with the number of arguments specified by ``argc``.
1504 On the stack are (in ascending order):
1505
1506 * The callable
1507 * ``self`` or ``NULL``
1508 * The remaining positional arguments
1509
1510 ``argc`` is the total of the positional arguments, excluding ``self``.
1511
1512 ``CALL`` pops all arguments and the callable object off the stack,
1513 calls the callable object with those arguments, and pushes the return value
1514 returned by the callable object.
1515
1516 .. versionadded:: 3.11
1517
1518 .. versionchanged:: 3.13
1519 The callable now always appears at the same position on the stack.
1520
1521 .. versionchanged:: 3.13
1522 Calls with keyword arguments are now handled by :opcode:`CALL_KW`.
1523
1524
1525 .. opcode:: CALL_KW (argc)
1526
1527 Calls a callable object with the number of arguments specified by ``argc``,
1528 including one or more named arguments. On the stack are (in ascending order):
1529
1530 * The callable
1531 * ``self`` or ``NULL``
1532 * The remaining positional arguments
1533 * The named arguments
1534 * A :class:`tuple` of keyword argument names
1535
1536 ``argc`` is the total of the positional and named arguments, excluding ``self``.
1537 The length of the tuple of keyword argument names is the number of named arguments.
1538
1539 ``CALL_KW`` pops all arguments, the keyword names, and the callable object
1540 off the stack, calls the callable object with those arguments, and pushes the
1541 return value returned by the callable object.
1542
1543 .. versionadded:: 3.13
1544
1545
1546 .. opcode:: CALL_FUNCTION_EX (flags)
1547
1548 Calls a callable object with variable set of positional and keyword
1549 arguments. If the lowest bit of *flags* is set, the top of the stack
1550 contains a mapping object containing additional keyword arguments.
1551 Before the callable is called, the mapping object and iterable object
1552 are each "unpacked" and their contents passed in as keyword and
1553 positional arguments respectively.
1554 ``CALL_FUNCTION_EX`` pops all arguments and the callable object off the stack,
1555 calls the callable object with those arguments, and pushes the return value
1556 returned by the callable object.
1557
1558 .. versionadded:: 3.6
1559
1560
1561 .. opcode:: PUSH_NULL
1562
1563 Pushes a ``NULL`` to the stack.
1564 Used in the call sequence to match the ``NULL`` pushed by
1565 :opcode:`LOAD_METHOD` for non-method calls.
1566
1567 .. versionadded:: 3.11
1568
1569
1570 .. opcode:: MAKE_FUNCTION
1571
1572 Pushes a new function object on the stack built from the code object at ``STACK[-1]``.
1573
1574 .. versionchanged:: 3.10
1575 Flag value ``0x04`` is a tuple of strings instead of dictionary
1576
1577 .. versionchanged:: 3.11
1578 Qualified name at ``STACK[-1]`` was removed.
1579
1580 .. versionchanged:: 3.13
1581 Extra function attributes on the stack, signaled by oparg flags, were
1582 removed. They now use :opcode:`SET_FUNCTION_ATTRIBUTE`.
1583
1584
1585 .. opcode:: SET_FUNCTION_ATTRIBUTE (flag)
1586
1587 Sets an attribute on a function object. Expects the function at ``STACK[-1]``
1588 and the attribute value to set at ``STACK[-2]``; consumes both and leaves the
1589 function at ``STACK[-1]``. The flag determines which attribute to set:
1590
1591 * ``0x01`` a tuple of default values for positional-only and
1592 positional-or-keyword parameters in positional order
1593 * ``0x02`` a dictionary of keyword-only parameters' default values
1594 * ``0x04`` a tuple of strings containing parameters' annotations
1595 * ``0x08`` a tuple containing cells for free variables, making a closure
1596
1597 .. versionadded:: 3.13
1598
1599
1600 .. opcode:: BUILD_SLICE (argc)
1601
1602 .. index:: pair: built-in function; slice
1603
1604 Pushes a slice object on the stack. *argc* must be 2 or 3. If it is 2, implements::
1605
1606 end = STACK.pop()
1607 start = STACK.pop()
1608 STACK.append(slice(start, end))
1609
1610 if it is 3, implements::
1611
1612 step = STACK.pop()
1613 end = STACK.pop()
1614 start = STACK.pop()
1615 STACK.append(slice(start, end, step))
1616
1617 See the :func:`slice` built-in function for more information.
1618
1619
1620 .. opcode:: EXTENDED_ARG (ext)
1621
1622 Prefixes any opcode which has an argument too big to fit into the default one
1623 byte. *ext* holds an additional byte which act as higher bits in the argument.
1624 For each opcode, at most three prefixal ``EXTENDED_ARG`` are allowed, forming
1625 an argument from two-byte to four-byte.
1626
1627
1628 .. opcode:: CONVERT_VALUE (oparg)
1629
1630 Convert value to a string, depending on ``oparg``::
1631
1632 value = STACK.pop()
1633 result = func(value)
1634 STACK.append(result)
1635
1636 * ``oparg == 1``: call :func:`str` on *value*
1637 * ``oparg == 2``: call :func:`repr` on *value*
1638 * ``oparg == 3``: call :func:`ascii` on *value*
1639
1640 Used for implementing formatted string literals (f-strings).
1641
1642 .. versionadded:: 3.13
1643
1644
1645 .. opcode:: FORMAT_SIMPLE
1646
1647 Formats the value on top of stack::
1648
1649 value = STACK.pop()
1650 result = value.__format__("")
1651 STACK.append(result)
1652
1653 Used for implementing formatted string literals (f-strings).
1654
1655 .. versionadded:: 3.13
1656
1657 .. opcode:: FORMAT_WITH_SPEC
1658
1659 Formats the given value with the given format spec::
1660
1661 spec = STACK.pop()
1662 value = STACK.pop()
1663 result = value.__format__(spec)
1664 STACK.append(result)
1665
1666 Used for implementing formatted string literals (f-strings).
1667
1668 .. versionadded:: 3.13
1669
1670
1671 .. opcode:: MATCH_CLASS (count)
1672
1673 ``STACK[-1]`` is a tuple of keyword attribute names, ``STACK[-2]`` is the class
1674 being matched against, and ``STACK[-3]`` is the match subject. *count* is the
1675 number of positional sub-patterns.
1676
1677 Pop ``STACK[-1]``, ``STACK[-2]``, and ``STACK[-3]``. If ``STACK[-3]`` is an
1678 instance of ``STACK[-2]`` and has the positional and keyword attributes
1679 required by *count* and ``STACK[-1]``, push a tuple of extracted attributes.
1680 Otherwise, push ``None``.
1681
1682 .. versionadded:: 3.10
1683
1684 .. versionchanged:: 3.11
1685 Previously, this instruction also pushed a boolean value indicating
1686 success (``True``) or failure (``False``).
1687
1688
1689 .. opcode:: RESUME (context)
1690
1691 A no-op. Performs internal tracing, debugging and optimization checks.
1692
1693 The ``context`` oparand consists of two parts. The lowest two bits
1694 indicate where the ``RESUME`` occurs:
1695
1696 * ``0`` The start of a function, which is neither a generator, coroutine
1697 nor an async generator
1698 * ``1`` After a ``yield`` expression
1699 * ``2`` After a ``yield from`` expression
1700 * ``3`` After an ``await`` expression
1701
1702 The next bit is ``1`` if the RESUME is at except-depth ``1``, and ``0``
1703 otherwise.
1704
1705 .. versionadded:: 3.11
1706
1707 .. versionchanged:: 3.13
1708 The oparg value changed to include information about except-depth
1709
1710
1711 .. opcode:: RETURN_GENERATOR
1712
1713 Create a generator, coroutine, or async generator from the current frame.
1714 Used as first opcode of in code object for the above mentioned callables.
1715 Clear the current frame and return the newly created generator.
1716
1717 .. versionadded:: 3.11
1718
1719
1720 .. opcode:: SEND (delta)
1721
1722 Equivalent to ``STACK[-1] = STACK[-2].send(STACK[-1])``. Used in ``yield from``
1723 and ``await`` statements.
1724
1725 If the call raises :exc:`StopIteration`, pop the top value from the stack,
1726 push the exception's ``value`` attribute, and increment the bytecode counter
1727 by *delta*.
1728
1729 .. versionadded:: 3.11
1730
1731
1732 .. opcode:: HAVE_ARGUMENT
1733
1734 This is not really an opcode. It identifies the dividing line between
1735 opcodes in the range [0,255] which don't use their argument and those
1736 that do (``< HAVE_ARGUMENT`` and ``>= HAVE_ARGUMENT``, respectively).
1737
1738 If your application uses pseudo instructions or specialized instructions,
1739 use the :data:`hasarg` collection instead.
1740
1741 .. versionchanged:: 3.6
1742 Now every instruction has an argument, but opcodes ``< HAVE_ARGUMENT``
1743 ignore it. Before, only opcodes ``>= HAVE_ARGUMENT`` had an argument.
1744
1745 .. versionchanged:: 3.12
1746 Pseudo instructions were added to the :mod:`dis` module, and for them
1747 it is not true that comparison with ``HAVE_ARGUMENT`` indicates whether
1748 they use their arg.
1749
1750 .. deprecated:: 3.13
1751 Use :data:`hasarg` instead.
1752
1753 .. opcode:: CALL_INTRINSIC_1
1754
1755 Calls an intrinsic function with one argument. Passes ``STACK[-1]`` as the
1756 argument and sets ``STACK[-1]`` to the result. Used to implement
1757 functionality that is not performance critical.
1758
1759 The operand determines which intrinsic function is called:
1760
1761 +-----------------------------------+-----------------------------------+
1762 | Operand | Description |
1763 +===================================+===================================+
1764 | ``INTRINSIC_1_INVALID`` | Not valid |
1765 +-----------------------------------+-----------------------------------+
1766 | ``INTRINSIC_PRINT`` | Prints the argument to standard |
1767 | | out. Used in the REPL. |
1768 +-----------------------------------+-----------------------------------+
1769 | ``INTRINSIC_IMPORT_STAR`` | Performs ``import *`` for the |
1770 | | named module. |
1771 +-----------------------------------+-----------------------------------+
1772 | ``INTRINSIC_STOPITERATION_ERROR`` | Extracts the return value from a |
1773 | | ``StopIteration`` exception. |
1774 +-----------------------------------+-----------------------------------+
1775 | ``INTRINSIC_ASYNC_GEN_WRAP`` | Wraps an async generator value |
1776 +-----------------------------------+-----------------------------------+
1777 | ``INTRINSIC_UNARY_POSITIVE`` | Performs the unary ``+`` |
1778 | | operation |
1779 +-----------------------------------+-----------------------------------+
1780 | ``INTRINSIC_LIST_TO_TUPLE`` | Converts a list to a tuple |
1781 +-----------------------------------+-----------------------------------+
1782 | ``INTRINSIC_TYPEVAR`` | Creates a :class:`typing.TypeVar` |
1783 +-----------------------------------+-----------------------------------+
1784 | ``INTRINSIC_PARAMSPEC`` | Creates a |
1785 | | :class:`typing.ParamSpec` |
1786 +-----------------------------------+-----------------------------------+
1787 | ``INTRINSIC_TYPEVARTUPLE`` | Creates a |
1788 | | :class:`typing.TypeVarTuple` |
1789 +-----------------------------------+-----------------------------------+
1790 | ``INTRINSIC_SUBSCRIPT_GENERIC`` | Returns :class:`typing.Generic` |
1791 | | subscripted with the argument |
1792 +-----------------------------------+-----------------------------------+
1793 | ``INTRINSIC_TYPEALIAS`` | Creates a |
1794 | | :class:`typing.TypeAliasType`; |
1795 | | used in the :keyword:`type` |
1796 | | statement. The argument is a tuple|
1797 | | of the type alias's name, |
1798 | | type parameters, and value. |
1799 +-----------------------------------+-----------------------------------+
1800
1801 .. versionadded:: 3.12
1802
1803 .. opcode:: CALL_INTRINSIC_2
1804
1805 Calls an intrinsic function with two arguments. Used to implement functionality
1806 that is not performance critical::
1807
1808 arg2 = STACK.pop()
1809 arg1 = STACK.pop()
1810 result = intrinsic2(arg1, arg2)
1811 STACK.append(result)
1812
1813 The operand determines which intrinsic function is called:
1814
1815 +----------------------------------------+-----------------------------------+
1816 | Operand | Description |
1817 +========================================+===================================+
1818 | ``INTRINSIC_2_INVALID`` | Not valid |
1819 +----------------------------------------+-----------------------------------+
1820 | ``INTRINSIC_PREP_RERAISE_STAR`` | Calculates the |
1821 | | :exc:`ExceptionGroup` to raise |
1822 | | from a ``try-except*``. |
1823 +----------------------------------------+-----------------------------------+
1824 | ``INTRINSIC_TYPEVAR_WITH_BOUND`` | Creates a :class:`typing.TypeVar` |
1825 | | with a bound. |
1826 +----------------------------------------+-----------------------------------+
1827 | ``INTRINSIC_TYPEVAR_WITH_CONSTRAINTS`` | Creates a |
1828 | | :class:`typing.TypeVar` with |
1829 | | constraints. |
1830 +----------------------------------------+-----------------------------------+
1831 | ``INTRINSIC_SET_FUNCTION_TYPE_PARAMS`` | Sets the ``__type_params__`` |
1832 | | attribute of a function. |
1833 +----------------------------------------+-----------------------------------+
1834
1835 .. versionadded:: 3.12
1836
1837
1838 **Pseudo-instructions**
1839
1840 These opcodes do not appear in Python bytecode. They are used by the compiler
1841 but are replaced by real opcodes or removed before bytecode is generated.
1842
1843 .. opcode:: SETUP_FINALLY (target)
1844
1845 Set up an exception handler for the following code block. If an exception
1846 occurs, the value stack level is restored to its current state and control
1847 is transferred to the exception handler at ``target``.
1848
1849
1850 .. opcode:: SETUP_CLEANUP (target)
1851
1852 Like ``SETUP_FINALLY``, but in case of an exception also pushes the last
1853 instruction (``lasti``) to the stack so that ``RERAISE`` can restore it.
1854 If an exception occurs, the value stack level and the last instruction on
1855 the frame are restored to their current state, and control is transferred
1856 to the exception handler at ``target``.
1857
1858
1859 .. opcode:: SETUP_WITH (target)
1860
1861 Like ``SETUP_CLEANUP``, but in case of an exception one more item is popped
1862 from the stack before control is transferred to the exception handler at
1863 ``target``.
1864
1865 This variant is used in :keyword:`with` and :keyword:`async with`
1866 constructs, which push the return value of the context manager's
1867 :meth:`~object.__enter__` or :meth:`~object.__aenter__` to the stack.
1868
1869
1870 .. opcode:: POP_BLOCK
1871
1872 Marks the end of the code block associated with the last ``SETUP_FINALLY``,
1873 ``SETUP_CLEANUP`` or ``SETUP_WITH``.
1874
1875 .. opcode:: JUMP
1876 .. opcode:: JUMP_NO_INTERRUPT
1877
1878 Undirected relative jump instructions which are replaced by their
1879 directed (forward/backward) counterparts by the assembler.
1880
1881 .. opcode:: LOAD_CLOSURE (i)
1882
1883 Pushes a reference to the cell contained in slot ``i`` of the "fast locals"
1884 storage.
1885
1886 Note that ``LOAD_CLOSURE`` is replaced with ``LOAD_FAST`` in the assembler.
1887
1888 .. versionchanged:: 3.13
1889 This opcode is now a pseudo-instruction.
1890
1891
1892 .. opcode:: LOAD_METHOD
1893
1894 Optimized unbound method lookup. Emitted as a ``LOAD_ATTR`` opcode
1895 with a flag set in the arg.
1896
1897
1898 .. _opcode_collections:
1899
1900 Opcode collections
1901 ------------------
1902
1903 These collections are provided for automatic introspection of bytecode
1904 instructions:
1905
1906 .. versionchanged:: 3.12
1907 The collections now contain pseudo instructions and instrumented
1908 instructions as well. These are opcodes with values ``>= MIN_PSEUDO_OPCODE``
1909 and ``>= MIN_INSTRUMENTED_OPCODE``.
1910
1911 .. data:: opname
1912
1913 Sequence of operation names, indexable using the bytecode.
1914
1915
1916 .. data:: opmap
1917
1918 Dictionary mapping operation names to bytecodes.
1919
1920
1921 .. data:: cmp_op
1922
1923 Sequence of all compare operation names.
1924
1925
1926 .. data:: hasarg
1927
1928 Sequence of bytecodes that use their argument.
1929
1930 .. versionadded:: 3.12
1931
1932
1933 .. data:: hasconst
1934
1935 Sequence of bytecodes that access a constant.
1936
1937
1938 .. data:: hasfree
1939
1940 Sequence of bytecodes that access a :term:`free (closure) variable <closure variable>`.
1941 'free' in this context refers to names in the current scope that are
1942 referenced by inner scopes or names in outer scopes that are referenced
1943 from this scope. It does *not* include references to global or builtin scopes.
1944
1945
1946 .. data:: hasname
1947
1948 Sequence of bytecodes that access an attribute by name.
1949
1950
1951 .. data:: hasjump
1952
1953 Sequence of bytecodes that have a jump target. All jumps
1954 are relative.
1955
1956 .. versionadded:: 3.13
1957
1958 .. data:: haslocal
1959
1960 Sequence of bytecodes that access a local variable.
1961
1962
1963 .. data:: hascompare
1964
1965 Sequence of bytecodes of Boolean operations.
1966
1967 .. data:: hasexc
1968
1969 Sequence of bytecodes that set an exception handler.
1970
1971 .. versionadded:: 3.12
1972
1973
1974 .. data:: hasjrel
1975
1976 Sequence of bytecodes that have a relative jump target.
1977
1978 .. deprecated:: 3.13
1979 All jumps are now relative. Use :data:`hasjump`.
1980
1981
1982 .. data:: hasjabs
1983
1984 Sequence of bytecodes that have an absolute jump target.
1985
1986 .. deprecated:: 3.13
1987 All jumps are now relative. This list is empty.
1988