identifying invoking module from imported function

Fredrik Lundh fredrik at pythonware.com
Thu May 6 18:27:29 EDT 1999


Andy Beall <beall at space.mit.edu> wrote:
> Is it possible to for a called function to identify the name of a module
> from which the function was called when that function resides in a
> module that was imported into the first module?  I guess I'm looking for
> something like __name__ but which will give the name of the "parent"
> module.  Here's an example of what I'm trying to find:
> 
> ------------------------ scriptA.py -------------------------------
> import scriptB
> foo()
> 
> ------------------------ scriptB.py -------------------------------
> def foo():
>     print 'Name of this module is ', __name__
>     print 'Name of calling module is ', ?????
> 
> ----------------------- DESIRED OUTPUT ---------------------
> >>> scriptB
> >>> scriptA

------------------------ scriptA.py -------------------------------
import scriptB
scriptB.foo()

------------------------ scriptB.py -------------------------------
import sys

def who_called_me():
    try:
        raise None
    except:
        c = sys.exc_traceback.tb_frame.f_back.f_back.f_code
        return c.co_filename, c.co_name

def foo():
    print 'Name of this module is ', __name__
    print 'Name of calling module is ', who_called_me()

</F>





More information about the Python-list mailing list