Is there any way to unimport a library
alex23
wuwei23 at gmail.com
Sun Nov 20 23:58:33 EST 2011
On Nov 21, 1:15 am, Gelonida N <gelon... at gmail.com> 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.
>
> My usecase is following:
>
> 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
> if not success:
> . . .
>
> Basically if I am not amble to import lib1_version1 AND lib2_version1,
> then I wanted to make sure, that lib1_version1 does not waste any memory
A simple way would be to create packages for each version that import
the two dependencies:
/version1/__init__.py:
import lib1_version1 as lib1
import lib2_version2 as lib2
/version2/__init__.py:
import lib1_version2 as lib1
import lib2_version2 as lib2
Then create a single module to handle the importing:
/libraries.py:
__all__ = ['lib1', 'lib2', 'version']
version = None
_import_errs = []
try:
from version1 import lib1, lib2
version = 1
except ImportError as (err,):
_import_errs.append(err)
if version is None:
try:
from version2 import lib1, lib2
version = 2
except ImportError as (err,):
_import_errs.append(err)
if version is None:
_format_errs = (('v%d: %s' % (ver, err)) for ver, err in
enumerate(_import_errs, 1))
raise ImportError('Unable to import libraries: %s' %
list(_format_errs))
More information about the Python-list
mailing list