Check if module is installed

Steven D'Aprano steve at
Tue Aug 5 01:12:49 CEST 2008

On Mon, 04 Aug 2008 05:25:08 -0700, Kless wrote:

> How to check is a library/module is installed on the system? I use the
> next code but it's possivle that there is a best way.
> -------------------
> try:
>     import foo
>     foo_loaded = True
> except ImportError:
>     foo_loaded = False
> -------------------

The "best" way depends on what you expect to do if the module can't be 
imported. What's the purpose of foo_loaded? If you want to know whether 
foo exists, then you can do this:

except NameError:
    print "foo doesn't exist"


    import foo
except ImportError:
    foo = None
x = "something"
if foo:
    y = foo.function(x)

If the module is required, and you can't do without it, then just fail 
gracefully when it's not available:

import foo  # fails gracefully with a traceback

Since you can't continue without foo, you might as well not even try. If 
you need something more complicated:

    import foo
except ImportError:
    log(module not found)
    print "FAIL!!!"
# any other exception is an unexpected error and 
# will fail with a traceback

Here's a related technique:

    from module import parrot  # fast version
except ImportError:
    # fallback to slow version
    def parrot(s='pining for the fjords'):
        return "It's not dead, it's %s." % s


More information about the Python-list mailing list