Given a frame object, I need to get the corresponding module object. In other words, implement callers\_module so this works:

```
import sys
from some_other_module import callers_module
assert sys.modules[__name__] is callers_module()

```

(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.)

I've attempted this:

```
import inspect
def callers_module():
  return inspect.currentframe().f_back

```

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—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.

It feels like I'm missing something simple. What needs to be done for this to work?