How to get the module from which the currently executing function was called?

Viewed 1930

This is my best solution so far to the problem of accessing the calling module from within a function:

import inspect
import sys
def calling_module(level=0):
    filename = inspect.stack()[level+2][1]
    modulename = inspect.getmodulename(filename)
    try:
        return sys.modules[modulename]
    except KeyError:
        return sys.modules['__main__']

...but implicit in the handling of the KeyError is the (largely unfounded) assumption that it can happen only if filename is being run as __main__.

Does the Python standard library provide a more robust way to do this?

1 Answers
Related