import, from and reload

Dave Benjamin ramen at lackingtalent.com
Thu Mar 2 13:01:35 EST 2006


On Thu, 2 Mar 2006, John Salerno wrote:

> I understand that after you import something once, you can reload it to pick 
> up new changes. But does reload work with from statements? I tried this:
>
> from X import *
>
> and then did my testing. I changed X and tried to reload it, but that didn't 
> seem to work. I figure the reason is because the module itself doesn't exist 
> as an object, only its names do. But I couldn't figure out how to pick up my 
> new changes at this point. I think eventually I did
>
> import X
>
> and that sort of started me back from the beginning, with my changes. But is 
> there a way to continue to use a from statement instead, and then reload your 
> changes?

"reload" is an ordinary procedure that takes a module as an argument. When 
you use a "from X import *" statement, "X" is not imported, so you have no 
module object to pass to "reload". In addition, even if you do import "X" 
and reload it, you won't update your bindings; you'll still have to do 
"from X import *" again to update any names imported from X before.

So, to make a long story short, you have to do something like:

import X
reload(X)
del X # to keep your namespace clean
from X import *

In general, "from X import *" should be avoided anyway, for reasons that 
have been discussed many times in the past. The annoyance with reloading 
is just one more reason. Better to just use "import X" in the first place.

-- 
    .:[ dave benjamin -( ramen/sp00 )- http://spoomusic.com/ ]:.
    "one man's constant is another man's variable" - alan perlis



More information about the Python-list mailing list