dis
--- Python 字节码反汇编器¶
Source code: Lib/dis.py
dis
模块通过反汇编支持CPython的 bytecode 分析。该模块作为输入的 CPython 字节码在文件 Include/opcode.h
中定义,并由编译器和解释器使用。
CPython 实现细节: 字节码是 CPython 解释器的实现细节。不保证不会在Python版本之间添加、删除或更改字节码。不应考虑将此模块的跨 Python VM 或 Python 版本的使用。
在 3.6 版更改: 每条指令使用2个字节。以前字节数因指令而异。
在 3.10 版更改: The argument of jump, exception handling and loop instructions is now the instruction offset rather than the byte offset.
在 3.11 版更改: Some instructions are accompanied by one or more inline cache entries,
which take the form of CACHE
instructions. These instructions
are hidden by default, but can be shown by passing show_caches=True
to
any dis
utility. Furthermore, the interpreter now adapts the
bytecode to specialize it for different runtime conditions. The
adaptive bytecode can be shown by passing adaptive=True
.
示例:给出函数 myfunc()
:
def myfunc(alist):
return len(alist)
the following command can be used to display the disassembly of
myfunc()
:
>>> dis.dis(myfunc)
2 0 RESUME 0
3 2 LOAD_GLOBAL 1 (NULL + len)
12 LOAD_FAST 0 (alist)
14 CALL 1
24 RETURN_VALUE
("2" 是行号)。
字节码分析¶
3.4 新版功能.
字节码分析 API 允许将 Python 代码片段包装在 Bytecode
对象中,以便轻松访问已编译代码的详细信息。
- class dis.Bytecode(x, *, first_line=None, current_offset=None, show_caches=False, adaptive=False)¶
分析的字节码对应于函数、生成器、异步生成器、协程、方法、源代码字符串或代码对象(由
compile()
返回)。这是下面列出的许多函数的便利包装,最值得注意的是
get_instructions()
,迭代于Bytecode
的实例产生字节码操作Instruction
的实例。如果 first_line 不是
None
,则表示应该为反汇编代码中的第一个源代码行报告的行号。否则,源行信息(如果有的话)直接来自反汇编的代码对象。如果 current_offset 不是
None
,则它指的是反汇编代码中的指令偏移量。设置它意味着dis()
将针对指定的操作码显示“当前指令”标记。If show_caches is
True
,dis()
will display inline cache entries used by the interpreter to specialize the bytecode.If adaptive is
True
,dis()
will display specialized bytecode that may be different from the original bytecode.- classmethod from_traceback(tb, *, show_caches=False)¶
从给定回溯构造一个
Bytecode
实例,将设置 current_offset 为异常负责的指令。
- codeobj¶
已编译的代码对象。
- first_line¶
代码对象的第一个源代码行(如果可用)
- info()¶
返回带有关于代码对象的详细信息的格式化多行字符串,如
code_info()
。
在 3.7 版更改: 现在可以处理协程和异步生成器对象。
在 3.11 版更改: Added the show_caches and adaptive parameters.
Example:
>>> bytecode = dis.Bytecode(myfunc)
>>> for instr in bytecode:
... print(instr.opname)
...
RESUME
LOAD_GLOBAL
LOAD_FAST
CALL
RETURN_VALUE
分析函数¶
dis
模块还定义了以下分析函数,它们将输入直接转换为所需的输出。如果只执行单个操作,它们可能很有用,因此中间分析对象没用:
- dis.code_info(x)¶
返回格式化的多行字符串,其包含详细代码对象信息的用于被提供的函数、生成器、异步生成器、协程、方法、源代码字符串或代码对象。
请注意,代码信息字符串的确切内容是高度依赖于实现的,它们可能会在Python VM或Python版本中任意更改。
3.2 新版功能.
在 3.7 版更改: 现在可以处理协程和异步生成器对象。
- dis.show_code(x, *, file=None)¶
将提供的函数、方法。源代码字符串或代码对象的详细代码对象信息打印到 file (如果未指定 file ,则为
sys.stdout
)。这是
print(code_info(x), file=file)
的便捷简写,用于在解释器提示符下进行交互式探索。3.2 新版功能.
在 3.4 版更改: 添加 file 形参。
- dis.dis(x=None, *, file=None, depth=None, show_caches=False, adaptive=False)¶
反汇编 x 对象。 x 可以表示模块、类、方法、函数、生成器、异步生成器、协程、代码对象、源代码字符串或原始字节码的字节序列。对于模块,它会反汇编所有功能。对于一个类,它反汇编所有方法(包括类和静态方法)。对于代码对象或原始字节码序列,它每字节码指令打印一行。它还递归地反汇编嵌套代码对象(推导式代码,生成器表达式和嵌套函数,以及用于构建嵌套类的代码)。在被反汇编之前,首先使用
compile()
内置函数将字符串编译为代码对象。如果未提供任何对象,则此函数会反汇编最后一次回溯。如果提供的话,反汇编将作为文本写入提供的 file 参数,否则写入
sys.stdout
。递归的最大深度受 depth 限制,除非它是
None
。depth=0
表示没有递归。If show_caches is
True
, this function will display inline cache entries used by the interpreter to specialize the bytecode.If adaptive is
True
, this function will display specialized bytecode that may be different from the original bytecode.在 3.4 版更改: 添加 file 形参。
在 3.7 版更改: 实现了递归反汇编并添加了 depth 参数。
在 3.7 版更改: 现在可以处理协程和异步生成器对象。
在 3.11 版更改: Added the show_caches and adaptive parameters.
- dis.distb(tb=None, *, file=None, show_caches=False, adaptive=False)¶
如果没有传递,则使用最后一个回溯来反汇编回溯的堆栈顶部函数。 指示了导致异常的指令。
如果提供的话,反汇编将作为文本写入提供的 file 参数,否则写入
sys.stdout
。在 3.4 版更改: 添加 file 形参。
在 3.11 版更改: Added the show_caches and adaptive parameters.
- dis.disassemble(code, lasti=- 1, *, file=None, show_caches=False, adaptive=False)¶
- dis.disco(code, lasti=- 1, *, file=None, show_caches=False, adaptive=False)¶
反汇编代码对象,如果提供了 lasti ,则指示最后一条指令。输出分为以下几列:
行号,用于每行的第一条指令
当前指令,表示为
-->
,一个标记的指令,用
>>
表示,指令的地址,
操作码名称,
操作参数,和
括号中参数的解释。
参数解释识别本地和全局变量名称、常量值、分支目标和比较运算符。
如果提供的话,反汇编将作为文本写入提供的 file 参数,否则写入
sys.stdout
。在 3.4 版更改: 添加 file 形参。
在 3.11 版更改: Added the show_caches and adaptive parameters.
- dis.get_instructions(x, *, first_line=None, show_caches=False, adaptive=False)¶
在所提供的函数、方法、源代码字符串或代码对象中的指令上返回一个迭代器。
迭代器生成一系列
Instruction
,命名为元组,提供所提供代码中每个操作的详细信息。如果 first_line 不是
None
,则表示应该为反汇编代码中的第一个源代码行报告的行号。否则,源行信息(如果有的话)直接来自反汇编的代码对象。The show_caches and adaptive parameters work as they do in
dis()
.3.4 新版功能.
在 3.11 版更改: Added the show_caches and adaptive parameters.
- dis.findlinestarts(code)¶
This generator function uses the
co_lines
method of the code object code to find the offsets which are starts of lines in the source code. They are generated as(offset, lineno)
pairs.在 3.6 版更改: 行号可能会减少。 以前,他们总是在增加。
在 3.10 版更改: The PEP 626
co_lines
method is used instead of theco_firstlineno
andco_lnotab
attributes of the code object.
- dis.findlabels(code)¶
检测作为跳转目标的原始编译后字节码字符串 code 中的所有偏移量,并返回这些偏移量的列表。
- dis.stack_effect(opcode, oparg=None, *, jump=None)¶
使用参数 oparg 计算 opcode 的堆栈效果。
如果代码有一个跳转目标并且 jump 是
True
,则drag_effect()
将返回跳转的堆栈效果。如果 jump 是False
,它将返回不跳跃的堆栈效果。如果 jump 是None
(默认值),它将返回两种情况的最大堆栈效果。3.4 新版功能.
在 3.8 版更改: 添加 jump 参数。
Python字节码说明¶
get_instructions()
函数和 Bytecode
类提供字节码指令的详细信息的 Instruction
实例:
- class dis.Instruction¶
字节码操作的详细信息
- opname¶
人类可读的操作名称
- arg¶
操作的数字参数(如果有的话),否则为
None
- argval¶
resolved arg value (if any), otherwise
None
- argrepr¶
human readable description of operation argument (if any), otherwise an empty string.
- offset¶
在字节码序列中启动操作索引
- starts_line¶
行由此操作码(如果有)启动,否则为
None
- is_jump_target¶
如果其他代码跳到这里,则为
True
,否则为False
- positions¶
dis.Positions
object holding the start and end locations that are covered by this instruction.
3.4 新版功能.
在 3.11 版更改: Field
positions
is added.
- class dis.Positions¶
In case the information is not available, some fields might be
None
.- lineno¶
- end_lineno¶
- col_offset¶
- end_col_offset¶
3.11 新版功能.
Python编译器当前生成以下字节码指令。
一般指令
In the following, We will refer to the interpreter stack as STACK and describe
operations on it as if it was a Python list. The top of the stack corresponds to
STACK[-1]
in this language.
- NOP¶
Do nothing code. Used as a placeholder by the bytecode optimizer, and to generate line tracing events.
- POP_TOP¶
Removes the top-of-stack item.:
STACK.pop()
- END_FOR¶
Removes the top two values from the stack. Equivalent to POP_TOP; POP_TOP. Used to clean up at the end of loops, hence the name.
3.12 新版功能.
- COPY(i)¶
Push the i-th item to the top of the stack without removing it from its original location.:
assert i > 0 STACK.append(STACK[-i])
3.11 新版功能.
- SWAP(i)¶
Swap the top of the stack with the i-th element.:
STACK[-i], STACK[-1] = stack[-1], STACK[-i]
3.11 新版功能.
- CACHE¶
Rather than being an actual instruction, this opcode is used to mark extra space for the interpreter to cache useful data directly in the bytecode itself. It is automatically hidden by all
dis
utilities, but can be viewed withshow_caches=True
.Logically, this space is part of the preceding instruction. Many opcodes expect to be followed by an exact number of caches, and will instruct the interpreter to skip over them at runtime.
Populated caches can look like arbitrary instructions, so great care should be taken when reading or modifying raw, adaptive bytecode containing quickened data.
3.11 新版功能.
一元操作
一元操作获取堆栈顶部元素,应用操作,并将结果推回堆栈。
- UNARY_NEGATIVE¶
Implements
STACK[-1] = -STACK[-1]
.
- UNARY_NOT¶
Implements
STACK[-1] = not STACK[-1]
.
- UNARY_INVERT¶
Implements
STACK[-1] = ~STACK[-1]
.
- GET_ITER¶
Implements
STACK[-1] = iter(STACK[-1])
.
- GET_YIELD_FROM_ITER¶
If
STACK[-1]
is a generator iterator or coroutine object it is left as is. Otherwise, implementsSTACK[-1] = iter(STACK[-1])
.3.5 新版功能.
Binary and in-place operations
Binary operations remove the top two items from the stack (STACK[-1]
and
STACK[-2]
). They perform the operation, then put the result back on the stack.
In-place operations are like binary operations, but the operation is done in-place
when STACK[-2]
supports it, and the resulting STACK[-1]
may be (but does
not have to be) the original STACK[-2]
.
- BINARY_OP(op)¶
Implements the binary and in-place operators (depending on the value of op).:
rhs = STACK.pop() lhs = STACK.pop() STACK.append(lhs op rhs)
3.11 新版功能.
- BINARY_SUBSCR¶
Implements:
key = STACK.pop() container = STACK.pop() STACK.append(container[index])
- STORE_SUBSCR¶
Implements:
key = STACK.pop() container = STACK.pop() value = STACK.pop() container[key] = value
- DELETE_SUBSCR¶
Implements:
key = STACK.pop() container = STACK.pop() del container[key]
- BINARY_SLICE¶
Implements:
end = STACK.pop() start = STACK.pop() container = STACK.pop() STACK.append(container[start:end])
3.12 新版功能.
- STORE_SLICE¶
Implements:
end = STACK.pop() start = STACK.pop() container = STACK.pop() values = STACK.pop() container[start:end] = value
3.12 新版功能.
协程操作码
- GET_AWAITABLE(where)¶
Implements
STACK[-1] = get_awaitable(STACK[-1])
, whereget_awaitable(o)
returnso
ifo
is a coroutine object or a generator object with the CO_ITERABLE_COROUTINE flag, or resolveso.__await__
.If the
where
operand is nonzero, it indicates where the instruction occurs:1
After a call to__aenter__
2
After a call to__aexit__
3.5 新版功能.
在 3.11 版更改: Previously, this instruction did not have an oparg.
- GET_AITER¶
Implements
STACK[-1] = STACK[-1].__aiter__()
.3.5 新版功能.
在 3.7 版更改: 已经不再支持从
__aiter__
返回可等待对象。
- GET_ANEXT¶
Implement
STACK.append(get_awaitable(STACK[-1].__anext__()))
to the stack. SeeGET_AWAITABLE
for details aboutget_awaitable
.3.5 新版功能.
- END_ASYNC_FOR¶
Terminates an
async for
loop. Handles an exception raised when awaiting a next item. The stack contains the async iterable inSTACK[-2]
and the raised exception inSTACK[-1]
. Both are popped. If the exception is notStopAsyncIteration
, it is re-raised.3.8 新版功能:
在 3.11 版更改: Exception representation on the stack now consist of one, not three, items.
- CLEANUP_THROW¶
Handles an exception raised during a
throw()
orclose()
call through the current frame. IfSTACK[-1]
is an instance ofStopIteration
, pop three values from the stack and push itsvalue
member. Otherwise, re-raiseSTACK[-1]
.3.12 新版功能.
- BEFORE_ASYNC_WITH¶
Resolves
__aenter__
and__aexit__
fromSTACK[-1]
. Pushes__aexit__
and result of__aenter__()
to the stack:STACK.extend((__aexit__, __aenter__())
3.5 新版功能.
其他操作码
- SET_ADD(i)¶
- Implements::
item = STACK.pop() set.add(STACK[-i], item)
Used to implement set comprehensions.
- LIST_APPEND(i)¶
Implements:
item = STACK.pop() list.append(STACK[-i], item)
Used to implement list comprehensions.
- MAP_ADD(i)¶
Implements:
value = STACK.pop() key = STACK.pop() dict.__setitem__(STACK[-i], key, value)
Used to implement dict comprehensions.
3.1 新版功能.
在 3.8 版更改: Map value is
STACK[-1]
and map key isSTACK[-2]
. Before, those were reversed.
对于所有 SET_ADD
、 LIST_APPEND
和 MAP_ADD
指令,当弹出添加的值或键值对时,容器对象保留在堆栈上,以便它可用于循环的进一步迭代。
- RETURN_VALUE¶
Returns with
STACK[-1]
to the caller of the function.
- RETURN_CONST(consti)¶
Returns with
co_consts[consti]
to the caller of the function.3.12 新版功能.
- YIELD_VALUE¶
Yields
STACK.pop()
from a generator.在 3.11 版更改: oparg set to be the stack depth.
在 3.12 版更改: oparg set to be the exception block depth, for efficient closing of generators.
- SETUP_ANNOTATIONS¶
检查
__annotations__
是否在locals()
中定义,如果没有,它被设置为空dict
。只有在类或模块体静态地包含 variable annotations 时才会发出此操作码。3.6 新版功能.
- POP_EXCEPT¶
Pops a value from the stack, which is used to restore the exception state.
在 3.11 版更改: Exception representation on the stack now consist of one, not three, items.
- RERAISE¶
Re-raises the exception currently on top of the stack. If oparg is non-zero, pops an additional value from the stack which is used to set
f_lasti
of the current frame.3.9 新版功能.
在 3.11 版更改: Exception representation on the stack now consist of one, not three, items.
- PUSH_EXC_INFO¶
Pops a value from the stack. Pushes the current exception to the top of the stack. Pushes the value originally popped back to the stack. Used in exception handlers.
3.11 新版功能.
- CHECK_EXC_MATCH¶
Performs exception matching for
except
. Tests whether theSTACK[-2]
is an exception matchingSTACK[-1]
. Pops STACK[-1] and pushes the boolean result of the test.3.11 新版功能.
- CHECK_EG_MATCH¶
Performs exception matching for
except*
. Appliessplit(STACK[-1])
on the exception group representingSTACK[-2]
.In case of a match, pops two items from the stack and pushes the non-matching subgroup (
None
in case of full match) followed by the matching subgroup. When there is no match, pops one item (the match type) and pushesNone
.3.11 新版功能.
- WITH_EXCEPT_START¶
Calls the function in position 4 on the stack with arguments (type, val, tb) representing the exception at the top of the stack. Used to implement the call
context_manager.__exit__(*exc_info())
when an exception has occurred in awith
statement.3.9 新版功能.
在 3.11 版更改: The
__exit__
function is in position 4 of the stack rather than 7. Exception representation on the stack now consist of one, not three, items.
- LOAD_ASSERTION_ERROR¶
将
AssertionError
推入栈顶。 由assert
语句使用。3.9 新版功能.
- LOAD_BUILD_CLASS¶
Pushes
builtins.__build_class__()
onto the stack. It is later called to construct a class.
- BEFORE_WITH¶
This opcode performs several operations before a with block starts. First, it loads
__exit__()
from the context manager and pushes it onto the stack for later use byWITH_EXCEPT_START
. Then,__enter__()
is called. Finally, the result of calling the__enter__()
method is pushed onto the stack.3.11 新版功能.
- GET_LEN¶
Perform
STACK.append(len(STACK[-1]))
.3.10 新版功能.
- MATCH_MAPPING¶
If
STACK[-1]
is an instance ofcollections.abc.Mapping
(or, more technically: if it has thePy_TPFLAGS_MAPPING
flag set in itstp_flags
), pushTrue
onto the stack. Otherwise, pushFalse
.3.10 新版功能.
- MATCH_SEQUENCE¶
If
STACK[-1]
is an instance ofcollections.abc.Sequence
and is not an instance ofstr
/bytes
/bytearray
(or, more technically: if it has thePy_TPFLAGS_SEQUENCE
flag set in itstp_flags
), pushTrue
onto the stack. Otherwise, pushFalse
.3.10 新版功能.
- MATCH_KEYS¶
STACK[-1]
is a tuple of mapping keys, andSTACK[-2]
is the match subject. IfSTACK[-2]
contains all of the keys inSTACK[-1]
, push atuple
containing the corresponding values. Otherwise, pushNone
.3.10 新版功能.
在 3.11 版更改: Previously, this instruction also pushed a boolean value indicating success (
True
) or failure (False
).
- STORE_NAME(namei)¶
Implements
name = STACK.pop()
. namei is the index of name in the attributeco_names
of the code object. The compiler tries to useSTORE_FAST
orSTORE_GLOBAL
if possible.
- DELETE_NAME(namei)¶
实现
del name
,其中 namei 是代码对象的co_names
属性的索引。
- UNPACK_SEQUENCE(count)¶
Unpacks
STACK[-1]
into count individual values, which are put onto the stack right-to-left.:STACK.extend(STACK.pop()[:count:-1])
- UNPACK_EX(counts)¶
Implements assignment with a starred target: Unpacks an iterable in
STACK[-1]
into individual values, where the total number of values can be smaller than the number of items in the iterable: one of the new values will be a list of all leftover items.The number of values before and after the list value is limited to 255.
The number of values before the list value is encoded in the argument of the opcode. The number of values after the list if any is encoded using an
EXTENDED_ARG
. As a consequence, the argument can be seen as a two bytes values where the low byte of counts is the number of values before the list value, the high byte of counts the number of values after it.The extracted values are put onto the stack right-to-left, i.e.
a, *b, c = d
will be stored after execution asSTACK.extend((a, b, c))
.
- STORE_ATTR(namei)¶
Implements:
obj = STACK.pop() value = STACK.pop() obj.name = value
where namei is the index of name in
co_names
.
- DELETE_ATTR(namei)¶
Implements:
obj = STACK.pop() del obj.name
where namei is the index of name into
co_names
.
- STORE_GLOBAL(namei)¶
类似于
STORE_NAME
但会将 name 存储为全局变量。
- DELETE_GLOBAL(namei)¶
类似于
DELETE_NAME
但会删除一个全局变量。
- LOAD_CONST(consti)¶
将
co_consts[consti]
推入栈顶。
- LOAD_NAME(namei)¶
将与
co_names[namei]
相关联的值推入栈顶。
- BUILD_TUPLE(count)¶
Creates a tuple consuming count items from the stack, and pushes the resulting tuple onto the stack.:
assert count > 0 STACK, values = STACK[:-count], STACK[-count:] STACK.append(tuple(values))
- BUILD_LIST(count)¶
类似于
BUILD_TUPLE
但会创建一个列表。
- BUILD_SET(count)¶
类似于
BUILD_TUPLE
但会创建一个集合。
- BUILD_MAP(count)¶
Pushes a new dictionary object onto the stack. Pops
2 * count
items so that the dictionary holds count entries:{..., STACK[-4]: STACK[-3], STACK[-2]: STACK[-1]}
.在 3.5 版更改: 字典是根据栈中的项创建而不是创建一个预设大小包含 count 项的空字典。
- BUILD_CONST_KEY_MAP(count)¶
The version of
BUILD_MAP
specialized for constant keys. Pops the top element on the stack which contains a tuple of keys, then starting fromSTACK[-2]
, pops count values to form values in the built dictionary.3.6 新版功能.
- BUILD_STRING(count)¶
拼接 count 个来自栈的字符串并将结果字符串推入栈顶。
3.6 新版功能.
- LIST_EXTEND(i)¶
Implements:
seq = STACK.pop() list.extend(STACK[-i], seq)
Used to build lists.
3.9 新版功能.
- SET_UPDATE(i)¶
Implements:
seq = STACK.pop() set.update(STACK[-i], seq)
Used to build sets.
3.9 新版功能.
- DICT_UPDATE(i)¶
Implements:
map = STACK.pop() dict.update(STACK[-i], map)
Used to build dicts.
3.9 新版功能.
- DICT_MERGE(i)¶
类似于
DICT_UPDATE
但对于重复的键会引发异常。3.9 新版功能.
- LOAD_ATTR(namei)¶
If the low bit of
namei
is not set, this replacesSTACK[-1]
withgetattr(STACK[-1], co_names[namei>>1])
.If the low bit of
namei
is set, this will attempt to load a method namedco_names[namei>>1]
from theSTACK[-1]
object.STACK[-1]
is popped. This bytecode distinguishes two cases: ifSTACK[-1]
has a method with the correct name, the bytecode pushes the unbound method andSTACK[-1]
.STACK[-1]
will be used as the first argument (self
) byCALL
when calling the unbound method. Otherwise,NULL
and the object return by the attribute lookup are pushed.在 3.12 版更改: If the low bit of
namei
is set, then aNULL
orself
is pushed to the stack before the attribute or unbound method respectively.
- COMPARE_OP(opname)¶
执行布尔运算操作。 操作名称可在
cmp_op[opname]
中找到。
- COMPARE_AND_BRANCH(opname)¶
Compares the top two values on the stack, popping them, then branches. The direction and offset of the jump is embedded as a
POP_JUMP_IF_TRUE
orPOP_JUMP_IF_FALSE
instruction immediately following the cache.3.12 新版功能.
- IS_OP(invert)¶
执行
is
比较,或者如果invert
为 1 则执行is not
。3.9 新版功能.
- CONTAINS_OP(invert)¶
执行
in
比较,或者如果invert
为 1 则执行not in
。3.9 新版功能.
- IMPORT_NAME(namei)¶
Imports the module
co_names[namei]
.STACK[-1]
andSTACK[-2]
are popped and provide the fromlist and level arguments of__import__()
. The module object is pushed onto the stack. The current namespace is not affected: for a proper import statement, a subsequentSTORE_FAST
instruction modifies the namespace.
- IMPORT_FROM(namei)¶
Loads the attribute
co_names[namei]
from the module found inSTACK[-1]
. The resulting object is pushed onto the stack, to be subsequently stored by aSTORE_FAST
instruction.
- JUMP_FORWARD(delta)¶
将字节码计数器的值增加 delta。
- JUMP_BACKWARD(delta)¶
Decrements bytecode counter by delta. Checks for interrupts.
3.11 新版功能.
- JUMP_BACKWARD_NO_INTERRUPT(delta)¶
Decrements bytecode counter by delta. Does not check for interrupts.
3.11 新版功能.
- POP_JUMP_IF_TRUE(delta)¶
If
STACK[-1]
is true, increments the bytecode counter by delta.STACK[-1]
is popped.在 3.11 版更改: The oparg is now a relative delta rather than an absolute target. This opcode is a pseudo-instruction, replaced in final bytecode by the directed versions (forward/backward).
在 3.12 版更改: This is no longer a pseudo-instruction.
- POP_JUMP_IF_FALSE(delta)¶
If
STACK[-1]
is false, increments the bytecode counter by delta.STACK[-1]
is popped.在 3.11 版更改: The oparg is now a relative delta rather than an absolute target. This opcode is a pseudo-instruction, replaced in final bytecode by the directed versions (forward/backward).
在 3.12 版更改: This is no longer a pseudo-instruction.
- POP_JUMP_IF_NOT_NONE(delta)¶
If
STACK[-1]
is notNone
, increments the bytecode counter by delta.STACK[-1]
is popped.This opcode is a pseudo-instruction, replaced in final bytecode by the directed versions (forward/backward).
3.11 新版功能.
在 3.12 版更改: This is no longer a pseudo-instruction.
- POP_JUMP_IF_NONE(delta)¶
If
STACK[-1]
isNone
, increments the bytecode counter by delta.STACK[-1]
is popped.This opcode is a pseudo-instruction, replaced in final bytecode by the directed versions (forward/backward).
3.11 新版功能.
在 3.12 版更改: This is no longer a pseudo-instruction.
- FOR_ITER(delta)¶
STACK[-1]
is an iterator. Call its__next__()
method. If this yields a new value, push it on the stack (leaving the iterator below it). If the iterator indicates it is exhausted then the byte code counter is incremented by delta.在 3.12 版更改: Up until 3.11 the iterator was popped when it was exhausted.
- LOAD_GLOBAL(namei)¶
Loads the global named
co_names[namei>>1]
onto the stack.在 3.11 版更改: If the low bit of
namei
is set, then aNULL
is pushed to the stack before the global variable.
- LOAD_FAST(var_num)¶
将指向局部对象
co_varnames[var_num]
的引用推入栈顶。在 3.12 版更改: This opcode is now only used in situations where the local variable is guaranteed to be initialized. It cannot raise
UnboundLocalError
.
- LOAD_FAST_CHECK(var_num)¶
Pushes a reference to the local
co_varnames[var_num]
onto the stack, raising anUnboundLocalError
if the local variable has not been initialized.3.12 新版功能.
- STORE_FAST(var_num)¶
Stores
STACK.pop()
into the localco_varnames[var_num]
.
- DELETE_FAST(var_num)¶
移除局部对象
co_varnames[var_num]
。
- MAKE_CELL(i)¶
Creates a new cell in slot
i
. If that slot is empty then that value is stored into the new cell.3.11 新版功能.
- LOAD_CLOSURE(i)¶
Pushes a reference to the cell contained in slot
i
of the "fast locals" storage. The name of the variable isco_fastlocalnames[i]
.Note that
LOAD_CLOSURE
is effectively an alias forLOAD_FAST
. It exists to keep bytecode a little more readable.在 3.11 版更改:
i
is no longer offset by the length ofco_varnames
.
- LOAD_DEREF(i)¶
Loads the cell contained in slot
i
of the "fast locals" storage. Pushes a reference to the object the cell contains on the stack.在 3.11 版更改:
i
is no longer offset by the length ofco_varnames
.
- LOAD_CLASSDEREF(i)¶
类似于
LOAD_DEREF
但在查询单元之前会首先检查局部对象字典。 这被用于加载类语句体中的自由变量。3.4 新版功能.
在 3.11 版更改:
i
is no longer offset by the length ofco_varnames
.
- STORE_DEREF(i)¶
Stores
STACK.pop()
into the cell contained in sloti
of the "fast locals" storage.在 3.11 版更改:
i
is no longer offset by the length ofco_varnames
.
- DELETE_DEREF(i)¶
Empties the cell contained in slot
i
of the "fast locals" storage. Used by thedel
statement.3.2 新版功能.
在 3.11 版更改:
i
is no longer offset by the length ofco_varnames
.
- COPY_FREE_VARS(n)¶
Copies the
n
free variables from the closure into the frame. Removes the need for special code on the caller's side when calling closures.3.11 新版功能.
- RAISE_VARARGS(argc)¶
使用
raise
语句的 3 种形式之一引发异常,具体形式取决于 argc 的值:0:
raise
(重新引发之前的异常)1:
raise STACK[-1]
(raise exception instance or type atSTACK[-1]
)2:
raise STACK[-2] from STACK[-1]
(raise exception instance or type atSTACK[-2]
with__cause__
set toSTACK[-1]
)
- CALL(argc)¶
Calls a callable object with the number of arguments specified by
argc
, including the named arguments specified by the precedingKW_NAMES
, if any. On the stack are (in ascending order), either:NULL
The callable
The positional arguments
The named arguments
or:
The callable
self
The remaining positional arguments
The named arguments
argc
is the total of the positional and named arguments, excludingself
when aNULL
is not present.CALL
pops all arguments and the callable object off the stack, calls the callable object with those arguments, and pushes the return value returned by the callable object.3.11 新版功能.
- CALL_FUNCTION_EX(flags)¶
调用一个可调用对象并附带位置参数和关键字参数变量集合。 如果设置了 flags 的最低位,则栈顶包含一个由额外关键字参数组成的映射对象。 在调用该可调用对象之前,映射对象和可迭代对象会被分别“解包”并将它们的内容分别作为关键字参数和位置参数传入。
CALL_FUNCTION_EX
会中栈中弹出所有参数及可调用对象,附带这些参数调用该可调用对象,并将可调用对象所返回的返回值推入栈顶。3.6 新版功能.
- PUSH_NULL¶
Pushes a
NULL
to the stack. Used in the call sequence to match theNULL
pushed byLOAD_METHOD
for non-method calls.3.11 新版功能.
- KW_NAMES(consti)¶
Prefixes
CALL
. Stores a reference toco_consts[consti]
into an internal variable for use byCALL
.co_consts[consti]
must be a tuple of strings.3.11 新版功能.
- MAKE_FUNCTION(flags)¶
将一个新函数对象推入栈顶。 从底端到顶端,如果参数带有指定的旗标值则所使用的栈必须由这些值组成。
0x01
一个默认值的元组,用于按位置排序的仅限位置形参以及位置或关键字形参0x02
一个仅限关键字形参的默认值的字典0x04
一个包含形参标注的字符串元组。0x08
一个包含用于自由变量的单元的元组,生成一个闭包the code associated with the function (at
STACK[-2]
)the qualified name of the function (at
STACK[-1]
)
在 3.10 版更改: 旗标值
0x04
是一个字符串元组而非字典。
- BUILD_SLICE(argc)¶
Pushes a slice object on the stack. argc must be 2 or 3. If it is 2, implements:
end = STACK.pop() start = STACK.pop() STACK.append(slice(start, stop))
if it is 3, implements:
step = STACK.pop() end = STACK.pop() start = STACK.pop() STACK.append(slice(start, end, step))
See the
slice()
built-in function for more information.
- EXTENDED_ARG(ext)¶
为任意带有大到无法放入默认的单字节的参数的操作码添加前缀。 ext 存放一个附加字节作为参数中的高比特位。 对于每个操作码,最多允许三个
EXTENDED_ARG
前缀,构成两字节到三字节的参数。
- FORMAT_VALUE(flags)¶
用于实现格式化字面值字符串(f-字符串)。 从栈中弹出一个可选的 fmt_spec,然后是一个必须的 value。 flags 的解读方式如下:
(flags & 0x03) == 0x00
: value 按原样格式化。(flags & 0x03) == 0x01
: 在格式化 value 之前调用其str()
。(flags & 0x03) == 0x02
: 在格式化 value 之前调用其repr()
。(flags & 0x03) == 0x03
: 在格式化 value 之前调用其ascii()
。(flags & 0x04) == 0x04
: 从栈中弹出 fmt_spec 并使用它,否则使用空的 fmt_spec。
使用
PyObject_Format()
执行格式化。 结果会被推入栈顶。3.6 新版功能.
- MATCH_CLASS(count)¶
STACK[-1]
is a tuple of keyword attribute names,STACK[-2]
is the class being matched against, andSTACK[-3]
is the match subject. count is the number of positional sub-patterns.Pop
STACK[-1]
,STACK[-2]
, andSTACK[-3]
. IfSTACK[-3]
is an instance ofSTACK[-2]
and has the positional and keyword attributes required by count andSTACK[-1]
, push a tuple of extracted attributes. Otherwise, pushNone
.3.10 新版功能.
在 3.11 版更改: Previously, this instruction also pushed a boolean value indicating success (
True
) or failure (False
).
- RESUME(where)¶
A no-op. Performs internal tracing, debugging and optimization checks.
The
where
operand marks where theRESUME
occurs:0
The start of a function, which is neither a generator, coroutine nor an async generator1
After ayield
expression2
After ayield from
expression3
After anawait
expression
3.11 新版功能.
- RETURN_GENERATOR¶
Create a generator, coroutine, or async generator from the current frame. Used as first opcode of in code object for the above mentioned callables. Clear the current frame and return the newly created generator.
3.11 新版功能.
- SEND(delta)¶
Equivalent to
STACK[-1] = STACK[-2].send(STACK[-1])
. Used inyield from
andawait
statements.If the call raises
StopIteration
, pop both items, push the exception'svalue
attribute, and increment the bytecode counter by delta.3.11 新版功能.
- HAVE_ARGUMENT¶
This is not really an opcode. It identifies the dividing line between opcodes in the range [0,255] which don't use their argument and those that do (
< HAVE_ARGUMENT
and>= HAVE_ARGUMENT
, respectively).If your application uses pseudo instructions, use the
hasarg
collection instead.在 3.6 版更改: 现在每条指令都带有参数,但操作码
< HAVE_ARGUMENT
会忽略它。 之前仅限操作码>= HAVE_ARGUMENT
带有参数。在 3.12 版更改: Pseudo instructions were added to the
dis
module, and for them it is not true that comparison withHAVE_ARGUMENT
indicates whether they use their arg.
- CALL_INTRINSIC_1¶
Calls an intrinsic function with one argument. Passes
STACK[-1]
as the argument and setsSTACK[-1]
to the result. Used to implement functionality that is necessary but not performance critical.The operand determines which intrinsic function is called:
0
Not valid1
Prints the argument to standard out. Used in the REPL.2
Performsimport *
for the named module.3
Extracts the return value from aStopIteration
exception.4
Wraps an aync generator value5
Performs the unary+
operation6
Converts a list to a tuple
3.12 新版功能.
- CALL_INTRINSIC_2¶
Calls an intrinsic function with two arguments. Passes
STACK[-2]
,STACK[-1]
as the arguments and setsSTACK[-1]
to the result. Used to implement functionality that is necessary but not performance critical.The operand determines which intrinsic function is called:
0
Not valid1
Calculates theExceptionGroup
to raise from atry-except*
.
3.12 新版功能.
Pseudo-instructions
These opcodes do not appear in python bytecode, they are used by the compiler but are replaced by real opcodes or removed before bytecode is generated.
- SETUP_FINALLY(target)¶
Set up an exception handler for the following code block. If an exception occurs, the value stack level is restored to its current state and control is transferred to the exception handler at
target
.
- SETUP_CLEANUP(target)¶
Like
SETUP_FINALLY
, but in case of exception also pushes the last instruction (lasti
) to the stack so thatRERAISE
can restore it. If an exception occurs, the value stack level and the last instruction on the frame are restored to their current state, and control is transferred to the exception handler attarget
.
- SETUP_WITH(target)¶
Like
SETUP_CLEANUP
, but in case of exception one more item is popped from the stack before control is transferred to the exception handler attarget
.This variant is used in
with
andasync with
constructs, which push the return value of the context manager's__enter__()
or__aenter__()
to the stack.
- POP_BLOCK¶
Marks the end of the code block associated with the last
SETUP_FINALLY
,SETUP_CLEANUP
orSETUP_WITH
.
- JUMP¶
- JUMP_NO_INTERRUPT¶
Undirected relative jump instructions which are replaced by their directed (forward/backward) counterparts by the assembler.
- LOAD_METHOD¶
Optimized unbound method lookup. Emitted as a
LOAD_ATTR
opcode with a flag set in the arg.
操作码集合¶
提供这些集合用于字节码指令的自动内省:
在 3.12 版更改: The collections now contain pseudo instructions as well. These are opcodes with values
>= MIN_PSEUDO_OPCODE
.
- dis.opname¶
操作名称的序列,可使用字节码来索引。
- dis.opmap¶
映射操作名称到字节码的字典
- dis.cmp_op¶
所有比较操作名称的序列。
- dis.hasarg¶
Sequence of bytecodes that use their argument.
3.12 新版功能.
- dis.hasconst¶
访问常量的字节码序列。
- dis.hasfree¶
访问自由变量的字节码序列(请注意这里所说的‘自由’是指在当前作用域中被内部作用域所引用的名称,或在外部作用域中被此作用域所引用的名称。 它 并不 包括对全局或内置作用域的引用)。
- dis.hasname¶
按名称访问属性的字节码序列。
- dis.hasjrel¶
具有相对跳转目标的字节码序列。
- dis.hasjabs¶
具有绝对跳转目标的字节码序列。
- dis.haslocal¶
访问局部变量的字节码序列。
- dis.hascompare¶
布尔运算的字节码序列。
- dis.hasexc¶
Sequence of bytecodes that set an exception handler.
3.12 新版功能.