从框架对象获取对执行堆栈上的功能对象的引用? [英] Obtaining references to function objects on the execution stack from the frame object?

查看:121
本文介绍了从框架对象获取对执行堆栈上的功能对象的引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出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.)

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

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?

推荐答案

以下是执行此操作的代码段.没有错误检查.这个想法是在祖父母的本地人中找到被调用的函数对象.返回的函数对象应该是父对象.如果您还想搜索内建函数,则只需查看stacks [2] [0] .f_builtins.

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]

对于一堂课,可以写以下内容(受Marcin解决方案启发)

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

这篇关于从框架对象获取对执行堆栈上的功能对象的引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆