Reputation: 20264
In playing with inspect
and reading the other questions here, I still cannot figure out how to get the function object of the caller more cleanly than to load the module by its path and then find the function within that.
In other words, how would you complete the following so that caller()
returns a method object?
import inspect
def caller():
frame = inspect.stack()[2]
code = frame[0]
path = frame[1]
line = frame[2]
name = frame[3] # function NAME string
# TODO: now what?
return func
def cry_wolf():
func = caller()
print "%s cried 'WOLF!'" % (func.__name__,)
def peter():
cry_wolf()
Remember, I already know the function name but what I'm trying to access is the function object that the calling code is running in. The result desired is:
peter cried 'WOLF!'
DONE! Thanks to user 61612, I have completed this code:
import imp, inspect, sys
def caller():
frame = inspect.stack()[2]
code = frame[0]
path = frame[1]
line = frame[2]
name = frame[3]
return code.f_globals[name]
def cry_wolf():
func = caller()
print "%s cried 'WOLF!'" % (func.__name__,)
def peter():
cry_wolf()
Awesome!
Upvotes: 3
Views: 1521
Reputation: 46533
Frame objects have the f_globals
attribute:
import inspect
def caller():
tup = inspect.stack()[2]
return tup[0].f_globals[tup[3]] # <function peter at address>
def cry_wolf():
func = caller()
print("%s cried 'WOLF!'" % (func.__name__,)) # peter cried 'WOLF!'
def peter():
cry_wolf()
Upvotes: 3