How to test if a module exists?

Jon Dufresne jon.dufresne at gmail.com
Sat Nov 6 14:22:08 EDT 2010


Hi,

My python program has an extension system where the extension can have
a optional magic python modules. Meaning if the extension module
exists, the program will use it and if not, it will continue without
the module. So my program tests if a module exists, if so use it,
otherwise continue. This is how I originally did this (pseudo code):


try:
    import extension_magic_module
except ImportError:
    pass
else:
    handle_extension_magic_module()


However, if the the extension module exists but throws an ImportError,
due to a bug in the extension this idiom will mask the error and I
will never see it. Later on in the program I will get unexpected
behavior because the module never successfully imported. I want the
program to fail if the extension module fails to import, but continue
if the module doesn't exist. Is there a correct way to handle this?


Jon



More information about the Python-list mailing list