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

编程入门 行业动态 更新时间:2024-10-28 04:16:47
本文介绍了从框架对象获取对执行堆栈上的功能对象的引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

更多推荐

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

本文发布于:2023-08-04 00:54:56,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1291476.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:对象   堆栈   框架   功能

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!