Yes but it doesn’t seem that dis.get_instructions() is able to
disassemble python modules.
That’s because a module is effectively just a namespace.
You can disassemble code from things which the module references.
Failing example:
>>> for I in dis.get_instructions(dis): print(I)
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/Cellar/python@3.10/3.10.6_1/Frameworks/Python.framework/Versions/3.10/lib/python3.10/dis.py", line 272, in get_instructions
co = _get_code_object(x)
File "/usr/local/Cellar/python@3.10/3.10.6_1/Frameworks/Python.framework/Versions/3.10/lib/python3.10/dis.py", line 148, in _get_code_object
raise TypeError("don't know how to disassemble %s objects" %
TypeError: don't know how to disassemble module objects
By constrast, asking to disassemble a function from inside the module
works:
>>> for I in dis.get_instructions(dis.dis): print(I)
...
Instruction(opname='LOAD_FAST', opcode=124, arg=0, argval='x', argrepr='x', offset=0, starts_line=52, is_jump_target=False)
Instruction(opname='LOAD_CONST', opcode=100, arg=1, argval=None, argrepr='None', offset=2, starts_line=None, is_jump_target=False)
Instruction(opname='IS_OP', opcode=117, arg=0, argval=0, argrepr='', offset=4, starts_line=None, is_jump_target=False)
Instruction(opname='POP_JUMP_IF_FALSE', opcode=114, arg=11, argval=22, argrepr='to 22', offset=6, starts_line=None, is_jump_target=False)
Instruction(opname='LOAD_GLOBAL', opcode=116, arg=0, argval='distb', argrepr='distb', offset=8, starts_line=53, is_jump_target=False)
Instruction(opname='LOAD_FAST', opcode=124, arg=1, argval='file', argrepr='file', offset=10, starts_line=None, is_jump_target=False)
and so on, because dis.dis
is a function, which has code.
You can use the dir()
builtin to find the names inside a module (or
other object):
>>> dir(dis)
['Bytecode', 'COMPILER_FLAG_NAMES', 'EXTENDED_ARG', 'FORMAT_VALUE', 'FORMAT_VALUE_CONVERTERS', 'HAVE_ARGUMENT', 'Instruction', 'MAKE_FUNCTION', 'MAKE_FUNCTION_FLAGS', '_Instruction', '_OPARG_WIDTH', '_OPNAME_WIDTH', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_disassemble_bytes', '_disassemble_recursive', '_disassemble_str', '_format_code_info', '_get_code_object', '_get_const_info', '_get_instructions_bytes', '_get_name_info', '_have_code', '_test', '_try_compile', '_unpack_opargs', 'cmp_op', 'code_info', 'collections', 'dis', 'disassemble', 'disco', 'distb', 'findlabels', 'findlinestarts', 'get_instructions', 'hascompare', 'hasconst', 'hasfree', 'hasjabs', 'hasjrel', 'haslocal', 'hasname', 'hasnargs', 'io', 'opmap', 'opname', 'pretty_flags', 'show_code', 'stack_effect', 'sys', 'types']
Cheers,
Cameron Simpson cs@cskk.id.au