unloading a module created with imp.new_module

Patrick Stinson patrickkidd at gmail.com
Tue Nov 25 07:56:05 CET 2014


> On Nov 24, 2014, at 2:44 AM, Ned Batchelder <ned at nedbatchelder.com> wrote:
> 
> On 11/23/14 5:10 AM, Patrick Stinson wrote:
>> I am defining a single class with a destructor method that prints
>> ‘__del__’, and running that source code string using exec with the
>> module’s dict like so:
>> 
>> import rtmidi
>> importsys
>> import types
>> importtime
>> importgc
>> 
>> s= """
>> class A:
>>     def __del__(self):
>>         print('__del__')
>> a = A()
>> """
>> 
>> m = types.ModuleType('mine')
>> exec(s, m.__dict__)
>> print('deleting...')
>> m= None
>> print('done')
>> 
>> and the output is:
>> 
>> deleting...
>> done
>> __del__
>> 
>> I the “__del__" to come between “deleting…” and “done”. This is not
>> being run from the interactive interpreter by via a .py file.
>> 
> 
> Let's look at this another way: Why do you need the module to be unloaded?  Isn't it enough to have the new code loaded?

I think that’s a good question. My original intention was to delete the module and everything contained in it since that’s what best matches what the user would expect by recompiling a script that they just created within this app. But the more I read and think, this purist perspective doesn’t make much sense.

The solution that I’ve come up with (which seems to be working really well so far), is to delete all objects in the module’s dict except the usual implicit objects (__import__, __name__, etc), then re-compile the code into the module’s dict. This even works well when I define QWidget gui objects, as they are hidden and deleted when the last reference goes away.

The main drawbacks for this approach are that the scripts exist in the same interpreter, and so can directly manipulate the app’s object hierarchy. But a user would have to go out of their way to do that so it’s their own fault if they break something :)

I would *love* to see code examples of how this sort of thing is done, where you write a GUI app in python that allows it’s users to write plugins for it in python using a built-in editor.

Thanks! Great thread


> 
> -- 
> Ned Batchelder, http://nedbatchelder.com <http://nedbatchelder.com/>
> 
> -- 
> https://mail.python.org/mailman/listinfo/python-list <https://mail.python.org/mailman/listinfo/python-list>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20141124/50e70a24/attachment.html>


More information about the Python-list mailing list