How to get current module object
John Machin
sjmachin at lexicon.net
Sun Feb 17 15:46:30 EST 2008
On Feb 18, 5:25 am, Alex <noname9... at gmail.com> wrote:
> Can I get reference to module object of current module (from which the
> code is currently executed)? I know __import__('filename') 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']
>>>
More information about the Python-list
mailing list