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?
I find that the following works well:
which I have inside a utility function called something like
printfunc()