identifying invoking module from imported function

Robin Becker robin at jessikat.demon.co.uk
Thu May 6 20:57:24 EDT 1999


In article <004501be980f$a4f45540$f29b12c2 at pythonware.com>, Fredrik
Lundh <fredrik at pythonware.com> writes
>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>
>
this gives me an error with 1.5.2; there're warnings about exc_traceback
being deprecated and about references to locals causing loops. I tried
instead

############
from sys import exc_info
def _tb():
        return exc_info()[2]
        
def who_called_me(n=0):
        try:
                raise None
        except:
                f = _tb().tb_frame.f_back
                while n>0:
                        t = f.f_back
                        if not hasattr(t,'f_code'): break
                        f = t
                        n = n - 1
                c = f.f_code
                return c.co_filename, c.co_name, f.f_lineno

if __name__=='__main__':
        import sys
        def test():
                print who_called_me()
        def test1():
                print who_called_me(1)
        def test2():
                print who_called_me(2)
        test()
        test1()
        test2()
#######
-- 
Robin Becker




More information about the Python-list mailing list