How to get current module object

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Alex

    How to get current module object

    Can I get reference to module object of current module (from which the
    code is currently executed)? I know __import__('fil ename') should
    probably do that, but the call contains redundant information (filename,
    which needs to be updated), and it'll perform unnecessary search in
    loaded modules list.

    It shouldn't be a real problem (filename can probably be extracted from
    the traceback anyway), but I wonder if there is more direct and less
    verbose way.

    Thanks
  • John Machin

    #2
    Re: How to get current module object

    On Feb 18, 5:25 am, Alex <noname9...@gma il.comwrote:
    Can I get reference to module object of current module (from which the
    code is currently executed)? I know __import__('fil ename') should
    probably do that, but the call contains redundant information (filename,
    which needs to be updated), and it'll perform unnecessary search in
    loaded modules list.
    >
    It shouldn't be a real problem (filename can probably be extracted from
    the traceback anyway), but I wonder if there is more direct and less
    verbose way.
    >
    Try this:

    C:\junk>type whoami.py
    def showme():
    import sys
    modname = globals()['__name__']
    print repr(modname)
    module = sys.modules[modname]
    print repr(module)
    print dir(module)


    C:\junk>python
    Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit
    (Intel)] on win32
    Type "help", "copyright" , "credits" or "license" for more information.
    >>import whoami
    >>whoami.showme ()
    'whoami'
    <module 'whoami' from 'whoami.py'>
    ['__builtins__', '__doc__', '__file__', '__name__', 'showme']
    >>>

    Comment

    Working...