How do I convert a python function/class/module object to a python code object
I have been looking around for some way to convert a function or class or module object in python to a python code object.
A few people accomplish this by doing inspect.getsource()
and compile()
, but the problem with this is that you are reading a potentially changed file, or if it was composed in the interactive python shell, you will just get an exception on getsource
.
I was wondering if anyone else may have a solution to this problem, so it can look something like this:
import dis
def func(arg):
x = 5
arg = 3
return x + arg
code_obj = function_to_code_obj(func)
dis.disassemble(code_obj)
and get the code object disassembly printed out like having created it using compile()
or parser.suite()
开发者_高级运维...
For a function you can use the func_code
attribute:
import dis
def func(arg):
x = 5
arg = 3
return x + arg
def function_to_code_obj(func):
return func.func_code
code_obj = function_to_code_obj(func)
dis.disassemble(code_obj)
精彩评论