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

前端 未结 11 1863
醉酒成梦
醉酒成梦 2020-12-05 01:30

I would like to be able to dynamically retrieve the current executing module or class name from within an imported module. Here is some code:

foo.py:

11条回答
  •  孤街浪徒
    2020-12-05 02:07

    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.

提交回复
热议问题