I need to find out function signature from bytecode. I am trying to add inspect functionality to disassembly, but get some problem.
Here is the source code to be compiled to bytecode:
>cat ~/tmp/func.py
x=100
def foo(n):
m = 10
return n + m
a=foo(x)
print(a)
Here is my modification of the dis package in Lib/dis.py:
import inspect **<== my edit**
def _disassemble_recursive(co, *, file=None, depth=None):
if depth is None or depth > 0:
if depth is not None:
depth = depth - 1
for x in co.co_consts:
if hasattr(x, 'co_code'):
print(file=file)
print("Disassembly of function ", x.co_name, x) **<== my edit**
sig = inspect.signature(x)
_disassemble_recursive(x, file=file, depth=depth)
After rebuilding Python, I get the following error in running disassembly:
>python3.7 -m dis ~/tmp/func.py
TypeError: <code object foo at 0x7fd594354ac0, file "~/tmp/func.py", line 2> is not a callable object
My immediate question is - how to get a callable from code object?
Maybe I am on the wrong track, the end goal is, I need to hack Python 3.7's disassembler so that I can get the signature of a function.
Appreciate your help.
This is a really bad way to get a code object's signature, but it's pretty cool to try.
Here's what I did:
import inspect
import types
def sig_from_code(code: types.CodeType):
return inspect.signature(
types.FunctionType(code, {})
)
Hope this helps :D
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.