Unloading a module

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Thu Oct 22 21:44:39 EDT 2009


En Thu, 22 Oct 2009 11:59:58 -0300, lallous <lallous at lgwm.org> escribió:

> If a reference to an imported module reaches zero will Python cleanup  
> everything related to that module and unload the compiled code, etc,  
> etc...?

The module object itself (as any other object whose reference count
reaches zero) will be destroyed. This in turn will decrement the reference
count of its namespace (its __dict__), and when that reaches zero it will
decrement the reference count of any object referenced (classes defined in
the module, global variables...). If there are no other references to
them, they will be destroyed too, as with any other object. It's always
the same story.

> For example:
>
> import sys
> m = [__import__(str(x)) for x in xrange(1,4)]
> del sys.modules['1']
> del m[0]
> print m
>
> Is module['1'] really unloaded or just it is not reachable but still  
> loaded?

Try with sys.getrefcount(the_module); when it reaches 2 you know
the_module is the last reference to the object [remember that getrefcount
always returns one more than the actual reference count]
In your example above, after the __import__ line, there are two references
to the module '1': one in sys.modules, and one in the m list. Once you
remove them (with del, as in your example), the module object itself is
destroyed, yes.

-- 
Gabriel Genellina




More information about the Python-list mailing list