Check if module is installed

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
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:

try:
    foo
except NameError:
    print "foo doesn't exist"

Alternatively:


try:
    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:

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


Here's a related technique:


try:
    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


-- 
Steven



More information about the Python-list mailing list