How to get a Function object from a Frame object

Steven Bethard steven.bethard at gmail.com
Mon Apr 18 13:50:46 EDT 2005


Gigi wrote:
> I need access to a function object that corresponds to a frame object in 
> a certain case from inside the function.
> 
> I can get the frame object using:
> 
> f = sys._getframe(0)
> 
> But the resulting frame object doesn't contain the information I need. 
> There is a lot of information in the code object (f.f_code), but not the 
>     actual function or method object.
> 
> The inspect module doesn't help either it just provides nicer interface 
> to the Frame object.
> 
> Any ideas out there?

Can you look up the code's co_name in the previous frame's locals?

py> def getself():
...    frame = sys._getframe(1)
...    return frame.f_back.f_locals[frame.f_code.co_name]
...
py> def g():
...     def h():
...         return getself()
...     return dict(g=getself(), h=h())
...
py> g()
{'h': <function h at 0x01194BB0>, 'g': <function g at 0x01194BF0>}

You probably also need to check the previous frame's globals...  And 
there are probably some cases where this code still wouldn't work...

STeVe



More information about the Python-list mailing list