title: Retrieve module object from stack frame
body: <p>Given a frame object, I need to get the corresponding module object.  In other words, implement callers_module so this works:</p>
  
  <pre><code>import sys
  from some_other_module import callers_module
  assert sys.modules[__name__] is callers_module()
  </code></pre>
  
  <p>(That would be equivalent because I can generate a stack trace in the function for this test case.  The imports are there simply to make that example complete and testable, and prevent callers_module from taking the shortcut of using __name__, since it's in a different module.)</p>
  
  <p>I've attempted this:</p>
  
  <pre><code>import inspect
  def callers_module():
    return inspect.currentframe().f_back
  </code></pre>
  
  <p>Which gets a frame object, on which f_code will give me a code object, but I can't find out how to get the corresponding module or its name (to use with sys.modules).  If I could get function objects, those have a __module__ attribute (and also have code objects), but that's not present in the frame.  Indeed, not all code objects belong to function objects, such as the code for my test case (with assert, above).  The same can be said of frame/code objects not having a module&mdash;but many of them do, and in my case they will, so that doesn't need to be handled; however, a simple None or exception is fine in that case, too.</p>
  
  <p>It feels like I'm missing something simple.  What needs to be done for this to work?</p>