import guards?

Erik Max Francis max at alcyone.com
Tue May 6 20:08:57 EDT 2003


Michael Mossey wrote:

> Does this do the work of importing math twice?

Nope.  Python caches imports in the same interpreter session, and so
won't do all the busywork of reading in file(s).  See:

max at oxygen:~/tmp% cat > guard.py
print "guard got imported"

def f(x): return x**2
^D
max at oxygen:~/tmp% cat > guardTest.py
import guard

print "guardTest got imported"
^D
max at oxygen:~/tmp% python
Python 2.2.2 (#2, Oct 14 2002, 17:32:20) 
[GCC egcs-2.91.66 19990314/Linux (egcs-1.1.2 release)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import guard
guard got imported
>>> guard.f(2)
4
>>> guard.f(3)
9
>>> import guard
>>> import guardTest
guardTest got imported

Once guard got imported, it didn't get imported again, even though the
module actually did something (print that message) when it got imported.
Note that you can enforce an explicit reload with the reload builtin:

>>> reload(guard)
guard got imported
<module 'guard' from 'guard.pyc'>

(The second line is the return value from the reload function; it
actually returns the module object you reloaded.)

-- 
 Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/
 __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE
/  \ Patiently, I'm still / Holding out until
\__/ Sandra St. Victor
    Bosskey.net: Unreal Tournament 2003 / http://www.bosskey.net/ut2k3/
 A personal guide to Unreal Tournament 2003.




More information about the Python-list mailing list