I want to check whether a library is installed and can be imported dynamically at runtime within an if statement to handle it properly.
I've tried the following code:
try:
import foo
print("Foo installed")
except ImportError:
print("Foo not installed")
It works as intended but does not seem like the most elegant method.
I was thinking more of a method that returns a boolean indicating whether the library is installed, something like:
Class.installed("foo") # returns a boolean
I want to check whether a library is installed and can be imported dynamically at runtime within an if statement to handle it properly.
I've tried the following code:
try:
import foo
print("Foo installed")
except ImportError:
print("Foo not installed")
It works as intended but does not seem like the most elegant method.
I was thinking more of a method that returns a boolean indicating whether the library is installed, something like:
Class.installed("foo") # returns a boolean
Share
Improve this question
edited Mar 10 at 21:56
toolic
62.3k21 gold badges79 silver badges128 bronze badges
asked Mar 10 at 21:55
ZheiranzZheiranz
111 bronze badge
2
|
2 Answers
Reset to default 1Use importlib.util
for a clean check.
import importlib.util
if importlib.util.find_spec("library_name") is not None:
print("Installed")
This code defines a function that checks if a package is installed:
def is_installed(pkg):
try:
__import__(pkg)
return True
except ImportError:
return False
if is_installed("foo"):
print("Foo installed")
else:
print("Foo not installed")
It uses __import__
, which allows to pass the name of the module to be imported as a string.
try
/except
is the accepted and usual method. – Tim Roberts Commented Mar 10 at 21:58