unloading a module created with imp.new_module

Steven D'Aprano steve at pearwood.info
Sun Nov 23 22:47:57 EST 2014


On Sat, 22 Nov 2014 21:49:32 -0900, Patrick Stinson wrote:

> If I create a module with imp.new_module(name), how can I unload it so
> that all the references contained in it are set to zero and the module
> is deleted? deleting the reference that is returned doesn’t seem to do
> the job, and it’s not in sys.modules, so where is the dangling
> reference?

It would be very surprising (although not impossible) if you have found a 
bug in the garbage collector. More likely you've just misinterpreted what 
you're seeing.

Can you please reply to the list with the simplest example of code that 
behaves in the way you are describing?

(If you reply to me privately, I may not get to see it for days or weeks, 
and when I do, my response will be to ask you to resend it to the list. 
So save all of us some time by replying directly to the list.)

If you're experimenting in the interactive interpreter, be aware that it 
holds onto a reference to the last few objects displayed. IPython can 
hold on to an unlimited number of such references, but the standard 
Python REPL only holds onto one. That can confound experimentation:


py> import imp, gc, types
py> mymodule = imp.new_module("mymodule")
py> [o for o in gc.get_objects() if isinstance(o, types.ModuleType) 
...  and o.__name__ == 'mymodule']
[<module 'mymodule' (built-in)>]
py> del mymodule
py> [o for o in gc.get_objects() if isinstance(o, types.ModuleType) 
...  and o.__name__ == 'mymodule']
[<module 'mymodule' (built-in)>]


It appears that the module isn't being garbage collected. But that's 
because the list [<mymodule>] is being held in the interactive 
interpreter's special _ variable. If we get rid of that by displaying 
something else, the module is garbage collected:


py> 23
23
py> [o for o in gc.get_objects() if isinstance(o, types.ModuleType) 
...  and o.__name__ == 'mymodule']
[]



-- 
Steven



More information about the Python-list mailing list