A Python function has a code object __code__.
A sys.settrace trace frame has a f_code code object.
For th
You can retrieve the function-object as an attribute of the module or the class:
import inspect
import sys
def frame_to_func(frame):
func_name = frame.f_code.co_name
if "self" in frame.f_locals:
return getattr(frame.f_locals["self"].__class__, func_name)
else:
return getattr(inspect.getmodule(frame), func_name)
def tracefunc(frame, event, arg):
if event in ['call', 'return']:
func_obj = frame_to_func(frame)
print(f"{event} {frame.f_code.co_name} {func_obj.__annotations__}")
def add(x: int, y: int) -> int:
return x+y
if __name__ == '__main__':
sys.settrace(tracefunc)
add(1, 2)
sys.settrace(None)
Output:
call add {'x':
The solution is inspired by this question.