globally available objects

Terry Reedy tjreedy at
Fri Oct 29 19:57:49 CEST 2004

"Steve" <lonetwin at> wrote in message 
news:5a309bd304102903342ca264f2 at
> I would like to create an object while importing a module only the
> first time it get's imported. I wonder imports already work in this
> manner.

As Diez said, yes.  From the viewpoint of Python code, a module is a Python 
object.  It particular, it is (has?) a separate namespace.  A module import 
statement is an abbreviated assignment statement.  It binds the object to 
the name indicated -- either its default 'fetch' name or the 'as' name.  So

import math as m
m == __import__('math')

are identical in effect.  If -- and only if -- the interpreter cannot find 
a module associated with that fetch name in its private dictionary of 
fetchname,module pairs (which CPython exposes as sys.modules), then it 
looks and executes code associated with that name.  The behind-the-scene 
details are implementation and version specific.

Even if you delete the association produced by import, the module object 
remains, ready to be reimported into any other module.  To force the 
interpreter to recreate the module from code, you need an explicit reload 

Terry J. Reedy

More information about the Python-list mailing list