How to test if a module exists?

Chris Rebert clp2 at rebertia.com
Sat Nov 6 19:35:26 CET 2010


On Sat, Nov 6, 2010 at 11:22 AM, Jon Dufresne <jon.dufresne at gmail.com> wrote:
> 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?

Here's what I came up with:

try:
    import extension_magic_module
except ImportError as err:
    if err.message != "No module named extension_magic_module":
        raise err
else:
    handle_extension_magic_module()

Cheers,
Chris
--
http://blog.rebertia.com



More information about the Python-list mailing list