Unloading a module

L

lallous

Hello Group,

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

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?

Thanks,
Elias
 
G

Gabriel Genellina

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,236
Members
46,825
Latest member
VernonQuy6

Latest Threads

Top