Home > python > Get the current module in Python

Get the current module in Python

December 31st, 2009 Leave a comment Go to comments

It’s sometimes useful to do introspection on the module itself you are writing. But python doesn’t provide any direct way to support this. In fact a PEP about this feature has been rejected.

A little google find a solution to this problem. Here’s the code

import sys
# get the current module's name
modname = globals()['__name__']
# get the module
module = sys.modules[modname]
# or more simply as suggested by E.T
module = sys.modules[__name__]
Tags:
  1. E.T
    December 31st, 2009 at 16:24 | #1

    import sys
    modname = globals()['__name__'] #can this line be omitted?

    module = sys.modules[__name__] #we can use __name__ directly, right?

  2. chenyufei
    December 31st, 2009 at 18:12 | #2

    Yes. I just copied that solution without much thinking …
    @E.T

  3. December 31st, 2009 at 20:25 | #3

    我正想说呢,除了主模块外,__name__就行了。

  4. January 2nd, 2010 at 12:27 | #4

    新年快乐!
    我的博客地址由 .cn 变为 .org,有空的时候更新一下友情链接吧。

  1. No trackbacks yet.