Is there any way to unimport a library
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Sun Nov 20 10:46:44 EST 2011
On Sun, 20 Nov 2011 16:15:05 +0100, Gelonida N wrote:
> I wondered whether there is any way to un-import a library, such, that
> it's occupied memory and the related shared libraries are released.
Not really. Python modules are objects, like everything else in Python,
and can only be deleted when the garbage collector is certain that
nothing else is keeping a reference to it. So long as any object,
anywhere, no matter how deep in your code or in third-party code, has a
reference to the module, you can't force it to be deleted.
You can remove it from your application's namespace:
import math
result = math.sin(1.2345)
del math
This, however, is not sufficient to free the module, as it is cached. You
can (but shouldn't!) do this as well:
import sys
del sys.modules['math']
But please don't delete modules from the cache unless (1) you really need
to, and (2) you are prepared for the consequences. "Just in case the
library uses too much memory" is not a good reason for deleting the
module.
The problem is, if you delete the module from the cache, but some other
part of your application still holds onto a reference to the module
(directly, or indirectly), the next time you import the library, Python
will not use the cached version but will create a second, independent
copy of the module in memory. Instead of saving memory, you have just
DOUBLED the amount of memory used by the library. You may also run into
bizarre, hard to debug problems due to breaking the "modules are
singletons" promise.
Trust me, this opens the door to a world of pain.
> success = False
> try:
> import lib1_version1 as lib1
> import lib2_version1 as lib2
> success = True
> except ImportError:
> pass
> if not success:
> try:
> import lib1_version2 as lib1
> import lib2_version2 as lib2
> success = True
> except importError:
> pass
Can you mix lib1_version1 and lib2_version2? If so, the best way of doing
this would be:
try:
import lib1_version1 as lib1
except ImportError:
try:
import lib1_version2 as lib1
except ImportError:
# Last chance. If this fails, it is a fatal error.
import lib1_version3 as lib1
And then do the same for lib2.
> One solution, that I could imagine is running the program a first time,
> detect all existing libraries and write out a config file being use the
> next time it is run, such, that immediately the right libs are imported.
What if the libs change between one run of your program and the next?
--
Steven
More information about the Python-list
mailing list