[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.python

How to get current module object

Unnamed One

2/17/2008 6:26:00 PM

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.

Thanks
1 Answer

John Machin

2/17/2008 8:47:00 PM

0

On Feb 18, 5:25 am, Alex <noname9...@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']
>>>