1

First of all, I must tell you that I have already looked this this bug and I understand that the feature is (in general) not possible for a long time. However, I have a use case which is very specific. Hence, I will try to describe my use case, and ask for suggestions.

I am writing an interactive python application which is run from the interpreter. So, the user might make a mistake or two when importing modules, and I would like it, if I could provide a method for the user to delete the module (as soon as he has imported it).

So, one of the problems with the references to the module being already incorporated into other objects is gone. Once, I am sure that the module has not been used at all, what can I do to remove it? Is it still technically possible?

I was thinking that if I could create a function which manually deletes every object/function created by the module when imported, then what I want might be accomplished. Is this true?

IPython does a similar operation with its extensions. Is that the correct way to go?

3
  • I can think of no reason to unload a module besides running out of memory. Is that why you are trying to do it? Commented Feb 3, 2013 at 12:20
  • No, I am not trying to unload it because it is running out of memory. I just think that modules which are not to be loaded should not be loaded. You can see that my use case is that of an interpreter as a workspace, so it would be good it there were no stray variables/functions around. Commented Feb 3, 2013 at 12:26
  • 1
    @OrangeHarvester: In that case just delete the references in the local namespace, no need to remove the module object from sys.modules too. Commented Feb 3, 2013 at 12:31

1 Answer 1

3

Modules are just a namespace, an object, stored in the sys.modules mapping.

If there are no other references to anything belonging in that module, you can remove it from the sys.modules mapping to delete it again:

>>> import timeit
>>> import sys
>>> del timeit  # remove local reference to the timeit module
>>> del sys.modules['timeit']  # remove module
Sign up to request clarification or add additional context in comments.

3 Comments

# remove local reference to the os module Is this correct? Or should it mean # remove local reference to the timeit module?
@OrangeHarvester: Yeah, missed that one. Because the os module is used throughout the stdlib for various purposes I thought better of using that one as an example, but forgot to update the comment. Thanks for pointing that out!
Thanks for the quick answer! I am learning python in a somewhat apprentice manner, (motivated by the application, not by the language right now), so I have pretty big gaps in some places. And this question did not throw up anything specific in my case.