从框架对象获取执行堆栈上函数对象的引用?
给定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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是执行此操作的代码片段。 没有错误检查。 这个想法是在祖父的局部变量中找到被调用的函数对象。 返回的函数对象应该是父对象。 如果您还想搜索内置函数,那么只需查看 stacks[2][0].f_builtins 即可。
对于类,可以编写以下内容(受 Marcin 解决方案的启发)
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.
In the case of a class, one can write the following (inspired by Marcin solution)
我采取了以下方法,与 Eolmar 的答案非常相似。
I took the following approach, very similar to Eolmar's answer.