unloading a module created with imp.new_module
ned at nedbatchelder.com
Mon Nov 24 12:21:43 CET 2014
On 11/24/14 2:25 AM, Patrick Stinson wrote:
> Basically, I have an app and am making it possible for the users to
> automate it by writing python scripts that run against the app's API. It
> includes PyQt5 widgets, a QScintilla editor, and a simple API for I/O.
> Apple’s app store is the plan.
> Right now I create a new module with types.ModuleType(‘something’), then
> exec the code in the module’s dict. Then when the user saves the script
> again in my editor, it deletes all top-level references in the module’s
> dict that don’t belong to the core list: ['__spec__', '__name__',
> '__loader__', '__package__', '__doc__', '__builtins__’] before running
> exec again.
> So far this seems to effectively “delete” the old module and re-compile
> it with the updated source. For example I can create Qt Widgets on the
> module level and they are safely deleted when the script is saved.
(BTW: the convention in most groups like this one is to bottom-post: put
your responses beneath the text you are responding to.)
Keep in mind that Python object have a reference to their class. If your
users are defining classes in their modules, and you instantiate the
class to create objects, then even when you reload updated code, the old
objects will still refer to the old classes. This is one of the things
that makes reloading modules in Python so difficult.
>> On Nov 23, 2014, at 5:56 PM, Ned Batchelder <ned at nedbatchelder.com
>> <mailto:ned at nedbatchelder.com>> wrote:
>> On 11/23/14 1:49 AM, 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?
>> This sounds tricky, and possible very difficult to do properly. Do
>> you mind if I ask what the larger problem is? Python might not be
>> very good at having modules come and go as you want.
>> Ned Batchelder, http://nedbatchelder.com
Ned Batchelder, http://nedbatchelder.com
More information about the Python-list