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")
This code defines a function that checks if a package is installed using __import__