How to retrieve the name of the calling module in Python
November 23, 2010 Comments
I was writing some Python code yesterday and I was wondering if there’s a way to retrieve the name of the module making the call to another module so I can log it automatically. I found this post that gives an example on how to do it using the built-in inspect module (I had to modify the sample code a little bit to make it work).
It looks like you can use this module to get information about the classes, methods, functions, traceback, and other objects as well. Sounds pretty useful for debugging.
import inspect def whoami(): '''Return the module name of where the call came from.''' # This will return a list of frame records, [1] is the frame # record of the caller. frame_records = inspect.stack()[1] # Index 1 of frame_records is the full path of the module, # we can then use inspect.getmodulename() to get the # module name from this path. calling_module = inspect.getmodulename(frame_records[1]) return calling_module # Test if __name__ == "__main__": print whoami()
It looks a little messy but it seems to work fine :D.