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?
I took the following approach, very similar to Eolmar's answer.
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)