Error when deleting and reimporting subpackages

Stephen Hansen me+list/python at ixokai.io
Mon Aug 22 17:56:07 EDT 2011


On Mon, Aug 22, 2011 at 12:14 PM, Matthew Brett <matthew.brett at gmail.com>wrote:

> Yes, sorry, I should have mentioned that I explored these kind of
> variations.
>
> I think I see that there isn't an obvious way for del sys.modules['apkg']
> to know to delete or modify 'apkg.subpkg', because sys.modules is just a
> dict.
>
> However, I could imagine the import machinery being able to recognize that
> 'apkg.subpkg' is broken, and re-import it without error.


> Is that reasonable?
>

Not really, no. Despite the fact that you can sorta do it, and that there's
this "reload" function, Python doesn't really support reloading of modules /
code. If you want to do it, you basically have to go out and _do_ it
yourself.

If you muck about in sys.modules, you need to do so completely. Python and
the import stuff won't really do anything to help you (though it won't go
out of its way to hinder you, either).

Something like:

def remove_module(name):
    for mod in sys.modules.keys():
        if mod == name or name.startswith(name + "."):
            del sys.modules[mod]

Then remove_module("apkg") may work for you. (Code above not tested at all,
not even kinda)

--Ix
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20110822/40a4c174/attachment-0001.html>


More information about the Python-list mailing list