title: Getting callable object from the frame
body: <p>Given the frame object (as returned by <a href="http://docs.python.org/library/sys.html#sys._getframe" rel="noreferrer">sys._getframe</a>, for instance), can I get the underlying callable object?</p>
  
  <p>Code explanation:</p>
  
  <pre><code>def foo():
      frame = sys._getframe()
      x = some_magic(frame)
  
      # x is foo, now
  </code></pre>
  
  <p>Note that my problem is getting the object out of a frame, not the currently called object. </p>
  
  <p>Hope that's possible.</p>
  
  <p>Cheers,</p>
  
  <p>MH</p>
  
  <p><b>EDIT:</b></p>
  
  <p>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!</p>
  
  <pre><code>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</code></pre>
  
  <p>(works in 2.6.2, for py3k replace <code>func_code</code> with <code>__code__</code> and <code>im_func</code> with <code>__func__</code>)</p>
  
  <p>Then, I can aggressively traverse globals() or gc.get_objects() and dir() everything in search for the callable with the given function object. </p>
  
  <p>Feels a bit unpythonic for me, but works.</p>
  
  <p>Thanks, again!</p>
  
  <p>MH</p>