Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 946
kjo Avatar asked Aug 10 '12 15:08

kjo


People also ask

How do I find the current module name?

A module can find out its own module name by looking at the predefined global variable __name__.

Which function is used to find out which names a module defines?

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.

How do I show a function module in Python?

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.

What is __ name __ in Python?

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.


1 Answers

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

like image 178
jmetz Avatar answered Sep 26 '22 18:09

jmetz