1

Just had the question pop into my mind.

Currently I code programs that are small and don't run for very long. But soon I'm looking to create programs that will run concurrently throughout the day. Perhaps in this program a module will be used initially, but then not be needed for vast portions of the day. Therefore, is it possible to unimport a module?

Upon searching I couldn't seem to find a 'yes' answer, so do I presume correctly that it's not actually possible in Python, even at the current time of writing?

The only function I know of deletes the reference, but not the actual import:

import module
module.X()
del module
module.X() 

_

Output: #NameError, can't find `module`
Phoenix
  • 4,386
  • 10
  • 40
  • 55
  • `del module` will delete the reference in the local namespace, but it will still be referenced from `sys.modules` in the least, so the module object itself won't get gc'ed (at least as long as I'm correct that `sys.modules` doesn't use weak refs, which I'm pretty sure it does not). – Silas Ray Feb 26 '14 at 15:15
  • possible duplicate of [Unload a module in Python](http://stackoverflow.com/questions/3105801/unload-a-module-in-python) – zhangxaochen Feb 26 '14 at 15:15
  • 2
    I don't know whether this is possible or not, but I suggest not worrying about it. Freeing a module isn't going to radically reduce your memory consumption or anything. – Kevin Feb 26 '14 at 15:16
  • 1
    @Kevin It's definitely *possible* (monkey with `sys.modules`, use `gc.get_referrers` to make sure the object has no references left, etc), the better question though is whether it is *practical* or *advisable*. If the memory footprint of your module is large enough that this would be worth it to you, there's probably more to be gained by refactoring so that you have less data living in module scope. – Silas Ray Feb 26 '14 at 15:17
  • 2
    see: http://bugs.python.org/issue9072 – zhangxaochen Feb 26 '14 at 15:23

1 Answers1

0

To free a module that is no longer used:

del module_name
del sys.modules[module_name]

If you go this route make sure to have an import for that module in any functions that need it.

Note that this will probably little, if any, effect on memory consumption.

Ethan Furman
  • 63,992
  • 20
  • 159
  • 237