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?
A module can find out its own module name by looking at the predefined global variable __name__.
The dir() function is used to find out all the names defined in a module. It returns a sorted list of strings containing the names defined in a module.
Method 1: Using the dir() Function: We have first to import the module in the Python shell, and then we have to write the module name in the dir() method, and it will return the list of all functions present in a particular Python module.
The __name__ variable (two underscores before and after) is a special Python variable. It gets its value depending on how we execute the containing script. Sometimes you write a script with functions that might be useful in other scripts as well. In Python, you can import that script as a module in another script.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With