Given the frame object (as returned by sys._getframe, for instance), can I get the underlying callable object?
Code explanation:
def foo():
frame = sys._getframe()
x = some_magic(frame)
# x is foo, now
Note that my problem is getting the object out of a frame, not the currently called object.
Hope that's possible.
Cheers,
MH
EDIT:
I've somewhat managed to work around this problem. It was heavily inspired by Andreas' and Alexander's replies. Thanks guys for the time invested!
def magic():
fr = sys._getframe(1)
for o in gc.get_objects():
if inspect.isfunction(o) and o.func_code is fr.f_code:
return o
class Foo(object):
def bar(self):
return magic()
x = Foo().bar()
assert x is Foo.bar.im_func
(works in 2.6.2, for py3k replace func_code
with __code__
and im_func
with __func__
)
Then, I can aggressively traverse globals() or gc.get_objects() and dir() everything in search for the callable with the given function object.
Feels a bit unpythonic for me, but works.
Thanks, again!
MH