Is there any way to unimport a library

Jean-Michel Pichavant jeanmichel at sequans.com
Mon Nov 21 08:06:18 EST 2011


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.
>
>
> 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
>
>
> At this moment this is more a thought excercise than a real issue, but I
> thought that perhaps somebody encountered this kind of issue and had an
> idea how to deal with such situations.
>
> 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.
>
>   
Short answer for unimporting modules : Not possible (yes there is a long 
one :o) ).

One approach to your problem is to test for module existence before 
importing any module.

import imp

def impVersion(version)
    try:
        imp.find_module('lib1_version%s' % version)
        imp.find_module('lib2_version%s' % version)
    except ImportError:
        raise
    else:
        lib1 = __import__('lib1_version%s' % version)
        lib2 = __import__('lib2_version%s' % version)

# using a for loop to avoid to many nested try statement
for version in [1,2,3,4]:
    try:
        impVersion(version)
    except ImportError:
        continue
    break

if not lib1 or not lib2:
    # no lib imported
    pass

Using this code allows you to import your library only if all conditions 
are met, preventing you from rolling back in case of error.

Jean-Michel



More information about the Python-list mailing list