Problem with Dynamically unloading a module

Carl Banks pavlovevidence at gmail.com
Wed Dec 23 18:18:10 EST 2009


On Dec 23, 7:40 am, Steven D'Aprano <st... at REMOVE-THIS-
cybersource.com.au> 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.
>
> >>> import math
> >>> del math
> >>> sys.modules['math'] = None
> >>> import math
>
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> ImportError: No module named math
>
> > # 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.

Actually, they won't.  Neither classes nor functions directly
reference their module; classes know their module only by name, and
functions only hold references to the module's namespace, not to the
module itself.  So if any references to functions defined in the
module remain, the module dict will stick around, but the module
itself may be collected.


> > But believe me, you don't want to mess up with the python import
> > mechanism.
>
> Unless you understand how it works.



Carl Banks



More information about the Python-list mailing list