Check if module is installed

K

Kless

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
 
C

Chris Ortner

try:
    import foo
    foo_loaded = True
except ImportError:
    foo_loaded = False

Many projects use this as the standard procedure to check a module's
presence. I assume, this is the best way.

Chris
 
S

Steven D'Aprano

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,997
Messages
2,570,241
Members
46,833
Latest member
BettyeMacf

Latest Threads

Top