Search code examples
pythonintrospection

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


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?


Solution

  • I find that the following works well:

    import inspect
    def printfunc()
        stk = inspect.stack()[1]
        mod = inspect.getmodule(stk[0])
        print("Currently in {}.{}".format(mod, stk[3]))
    

    which I have inside a utility function called something like printfunc()