Problem with Dynamically unloading a module

Jean-Michel Pichavant jeanmichel at sequans.com
Wed Dec 23 10:58:59 EST 2009


Steven D'Aprano wrote:
> On Wed, 23 Dec 2009 13:37:06 +0100, Jean-Michel Pichavant wrote:
>
>   
>> 3/ if you really need to unload the previous module, it's a little bit
>> tedious.
>>
>> import mod1
>> del mod1
>> sys.modules['mod1'] = None 
>>     
>
> Assigning sys.modules[name] to None is not the same as deleting the 
> entry. None has special meaning to imports from packages, and for modules 
> it is interpreted as meaning that the module doesn't exist.
>   
did'nt know that.

sys.modules.pop('mod1')

should then do the trick.
>> # will unload mod1 assuming mod1 was the only
>> reference to that module.
>>     
>
> Which is highly unlikely. Any classes or functions from the module will 
> keep the module alive.
>   

Yep.
This is why I strongly suggested the OP to use a static approach, 
unloading/reloading module in python isn't really the most obvious thing 
ever done. I would even dare to say that if it was possible, someone 
would have already written the module for it.

JM



More information about the Python-list mailing list