Re: various re-import errors
Wed, 13 Apr 1994 21:32:28 +0200

Jim Roskind:
> I am unclear on the meaning of a "dynamically loaded module."

Don't worry -- I meant a module implemented in C and loaded into the
Python process using any of a number of available dynamic object
loading schemes.

Lance Ellinghouse:
> > import stdwin
> > import sys
> > del sys.modules['stdwin']
> > import stdwin
> Actually I use this feature.. PLEASEE do not remove this ability...

This will continue to work for all modules implemented in Python
(including "frozen" modules) and for most built-in modules (but not
sys, __main__ and __builtin__); it may crash for built-in modules that
weren't designed to be initialized multiple times. On some platforms
dynamically loading the same object file or shared library twice is
not a good idea (since I have received reports of core dumps) so this
is explicitly forbidden.

> Correct me if I'm worng (of course you will!), but I thought
> deleting a module name from sys.modules and then 'import'ing the
> module again (note: import, NOT reload) was the same thing as
> reload(module). I was under the impression that sys.modules was the
> gatekeeper for the module cash. Is that not the case?

No, although the difference is subtle. Have a look at this example:

import string
string.stowaway = 'verstekeling'
old_string = string
import sys
del sys.modules['string']
import string
print string is old_string
print hasattr(old_string, 'stowaway')
print hasattr(string, 'stowaway')

This will print 0, 1 and 0 (i.e., string is not the same object as
old_string, old_string still has the variable stowaway, and the new
string modules doesn't).

However, this example:

import string
old_string = string
print string is old_string
print hasattr(old_string, 'stowaway')
print hasattr(string, 'stowaway')

will print 1, 1 and 1 -- string and old_string are different names for
the same module object.

This difference is occasionally useful by itself, but really necessary
because it means that after reload() of a module in one place, all
other modules that have imported it also see the new version of the
module. (However, if you have imported individual objects from it
using "from ... import ..." or otherwise stuck pointers to objects
from the module into other data structures,, these will not be
replaced by their new versions -- it would be impossible to trace

Hope this explains the situation a bit more...

--Guido van Rossum, CWI, Amsterdam <>
URL: <>