import & __import__

Moshe Zadka moshez at math.huji.ac.il
Mon Mar 13 00:18:37 EST 2000


On Sun, 12 Mar 2000, Chris Armstrong wrote:

> Hi all. I'm pretty much a newbie to Python, and I have a question about 
> import vs __import__. I'm implementing dynamically imported modules in
> a game I'm writing, and I need to use __import__ to do this. One thing I
> noticed is that __import__ doesn't seem to execute the modules that it
> imports, while import does.. The docs for __import__ don't mention anything
> about this, and I'm just curious about it. I tested this by making a simple
> module that just has `` print "Hi." '' in it. `` import modulename '' caused
> it to print out "Hi." while `` foobar = __import__("modulename") '' didn't.
> This isn't really important to me, I was just curious about it.

Nope:
moshe-bombei:/home/moshe>echo 'print "hi"' > moshe.py
moshe-bombei:/home/moshe>python
Python 1.5.2 (#1, Feb 21 2000, 14:52:33)  [GCC 2.95.2 19991024 (release)]
on sunos5
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
>>> import moshe
hi
>>> ^D
moshe-bombei:/home/moshe>python
Python 1.5.2 (#1, Feb 21 2000, 14:52:33)  [GCC 2.95.2 19991024 (release)]
on sunos5
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
>>> __import__("moshe")
hi
<module 'moshe' from 'moshe.pyc'>

Assumption: you did something like

>> import module
>> __import__("module")

The *second* import has no effect, since the module is already imported.
You just get a new reference to it.
--
Moshe Zadka <mzadka at geocities.com>. 
http://www.oreilly.com/news/prescod_0300.html





More information about the Python-list mailing list