Python – Get __name__ of calling function’s module in Python


Suppose myapp/ contains:

def info(msg):
    caller_name = ????
    print '[%s] %s' % (caller_name, msg)

And myapp/ contains:

import foo'Hello') # => [] Hello

I want caller_name to be set to the __name__ attribute of the calling functions' module (which is '') in this case. How can this be done?

Best Solution

Check out the inspect module:

inspect.stack() will return the stack information.

Inside a function, inspect.stack()[1] will return your caller's stack. From there, you can get more information about the caller's function name, module, etc.

See the docs for details:

Also, Doug Hellmann has a nice writeup of the inspect module in his PyMOTW series:

EDIT: Here's some code which does what you want, I think:

import inspect 

def info(msg):
    frm = inspect.stack()[1]
    mod = inspect.getmodule(frm[0])
    print '[%s] %s' % (mod.__name__, msg)