unloading a module created with imp.new_module

Ian Kelly ian.g.kelly at gmail.com
Sun Nov 23 10:56:34 CET 2014


On Sun, Nov 23, 2014 at 2:48 AM, Ian Kelly <ian.g.kelly at gmail.com> wrote:
> On Sat, Nov 22, 2014 at 11:49 PM, Patrick Stinson <patrickkidd at gmail.com> 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?
>
> How are you determining that the module is not deleted?

>From my testing, using Python 3.4:

>>> for i in range(5): imp.new_module('spam')
...
<module 'spam'>
<module 'spam'>
<module 'spam'>
<module 'spam'>
<module 'spam'>
>>> import gc, types
>>> [m for m in gc.get_objects() if isinstance(m, types.ModuleType) and m.__name__ == 'spam']
[<module 'spam'>]
>>> 42
42
>>> [m for m in gc.get_objects() if isinstance(m, types.ModuleType) and m.__name__ == 'spam']
[]

In this case one of the created modules was hanging around because it
was still referenced by the special "_" variable of the interactive
interpreter. Evaluating a new expression cleared that out and deleted
the module. Maybe you're seeing the same thing.



More information about the Python-list mailing list