Obtaining references to function objects on the execution stack from the frame object?

徘徊边缘 提交于 2019-12-08 23:02:31

Here is a code snippet that do it. There is no error checking. The idea is to find in the locals of the grand parent the function object that was called. The function object returned should be the parent. If you want to also search the builtins, then simply look into stacks[2][0].f_builtins.

def f():
    stacks  = inspect.stack()
    grand_parent_locals = stacks[2][0].f_locals
    caller_name = stacks[1][3]
    candidate = grand_parent_locals[caller_name]

In the case of a class, one can write the following (inspired by Marcin solution)

class test(object):
    def f(self):
        stack = inspect.stack()
        parent_func_name = stack[1][3]
        parent_func = getattr(self, parent_func_name).im_func

I took the following approach, very similar to Eolmar's answer.

stack = inspect.stack()
parent_locals = stack[1][0].f_locals['self']
parent_func_name = stack[1][3]
parent_func_attr = getattr(parent_locals,parent_func_name)
parent_func = parent_func_attr.im_func
is_parent_gen = inspect.isgeneratorfunction(func)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!