Getting the Python function for a code object

前端 未结 2 1163
借酒劲吻你
借酒劲吻你 2020-12-30 06:41

A Python function has a code object __code__.

A sys.settrace trace frame has a f_code code object.

For th

2条回答
  •  抹茶落季
    2020-12-30 07:02

    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': , 'y': , 'return': }

    The solution is inspired by this question.

提交回复
热议问题