从框架对象获取执行堆栈上函数对象的引用?

发布于 2024-07-25 17:35:45 字数 309 浏览 12 评论 0原文

给定inspect.stack()的输出,是否可以从堆栈帧的任何位置获取函数对象并调用它们? 如果是这样,怎么办?

(我已经知道如何获取函数的名称。)

这就是我的意思:假设我是一个函数,我试图确定我的调用者是生成器还是常规函数? 我需要在函数对象上调用 inspect.isgeneratorfunction() 。 您如何知道是谁给您打电话? inspect.stack(),对吗? 因此,如果我能以某种方式将它们放在一起,我就会得到我的问题的答案。 也许有一种更简单的方法可以做到这一点?

Given the output of inspect.stack(), is it possible to get the function objects from anywhere from the stack frame and call these? If so, how?

(I already know how to get the names of the functions.)

Here is what I'm getting at: Let's say I'm a function and I'm trying to determine if my caller is a generator or a regular function? I need to call inspect.isgeneratorfunction() on the function object. And how do you figure out who called you? inspect.stack(), right? So if I can somehow put those together, I'll have the answer to my question. Perhaps there is an easier way to do this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

后知后觉 2024-08-01 17:35:45

这是执行此操作的代码片段。 没有错误检查。 这个想法是在祖父的局部变量中找到被调用的函数对象。 返回的函数对象应该是父对象。 如果您还想搜索内置函数,那么只需查看 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]

对于类,可以编写以下内容(受 Marcin 解决方案的启发)

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

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
蒗幽 2024-08-01 17:35:45

我采取了以下方法,与 Eolmar 的答案非常相似。

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)

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)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文