reload fails if module not in sys.path

Steve Holden steve at
Fri Oct 21 02:05:35 CEST 2005

Lonnie Princehouse wrote:
> So, it turns out that reload() fails if the module being reloaded isn't
> in sys.path.
> Maybe it could fall back to module.__file__ if the module isn't found
> in sys.path??
> ... or reload could just take an optional path parameter...
> Or perhaps I'm the only one who thinks this is silly:
>>>>my_module = imp.load_module(module_name, *imp.find_module(module_name,path))
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> ImportError: No module named whatever
You appear to have failed to load some module called "whatever", which I 
presume is the value of module_name?
> I guess I could just deal with this by fiddling with sys.path or using
> imp.load_module again, but.. um.. I like to complain. ;-)
That's OK, but you may find fiddling with sys.path is more productive :-)

> The context here is that I'm loading user-defined modules as plugins,
> and I don't want to keep the plugin directory in sys.path because of
> potential module name conflicts.
Hmm. I know that if your module isn't in sys.modules your reload will fail:

 >>> import trPyCard # picking a moduule at random
 >>> import sys
 >>> del sys.modules['trPyCard']
 >>> reload(trPyCard)
Traceback (most recent call last):
   File "<stdin>", line 1, in ?
ImportError: reload(): module trPyCard not in sys.modules

Apart from that, it would seem sensible not to try and use reload if you 
haven't used a kosher import mechanism - there are many caveats on the 
reload() documentation, and the mechanisms it uses aren't spelled out 
anywhere but in the interpreter source.

It would seem easier just to ensure that the plugins directory(ies) 
appear first on sys.path and use __import__(). imp is high magic.

Steve Holden       +44 150 684 7255  +1 800 494 3119
Holden Web LLC           
PyCon TX 2006        

More information about the Python-list mailing list