How can I access the current executing module or class name in Python?

From the comment -- not the question.

I am simply curious to see if what I am trying to do is possible.

The answer to "is it possible" is always "yes". Always. Unless your question involves time travel, anti-gravity or perpetual motion.

Since the answer is always "yes", your question is ill-formed. The real question is "what's a good way to have my logging module know the name of the client?" or something like that.

The answer is "Accept it as a parameter." Don't mess around with inspecting or looking for mysterious globals or other tricks.

Just follow the design pattern of logging.getLogger() and use explicitly-named loggers. A common idiom is the following

logger= logging.getLogger( __name__ )

That handles almost all log naming perfectly.


This should work for referencing the current module:

import sys
sys.modules[__name__]

Tags:

Python

Module