Skip to main content

How to Check If a Library is Installed in Python

In dynamic Python applications, especially those distributing code across different environments (like CI/CD pipelines or shared servers), verifying whether a required library is installed before using it is critical. Attempting to import a missing module raises an ImportError.

This guide explores how to check for module installation using try-except blocks, importlib, and shell commands.

Method 1: Try-Import-Except (Standard Approach)

The most common Pythonic way to handle dependencies is the "Easier to Ask for Forgiveness than Permission" (EAFP) principle. Simply try to import the module and catch the ImportError (or ModuleNotFoundError) if it fails.

try:
import requests
print("Requests module is installed.")
except ImportError:
print("Requests module is NOT installed.")

Output:

Requests module is installed.

Handling Optional Dependencies

This pattern is excellent for optional features. If a module is missing, you can disable specific functionality rather than crashing the app.

try:
import matplotlib.pyplot as plt
HAS_MATPLOTLIB = True
except ImportError:
HAS_MATPLOTLIB = False

def plot_data(data):
if HAS_MATPLOTLIB:
plt.plot(data)
plt.show()
else:
print("Plotting unavailable: matplotlib is not installed.")

Method 2: Using importlib.util.find_spec (Robust Check)

If you want to check if a module is installed without actually importing it (which executes the module's top-level code), use the importlib library. This is safer for heavy libraries or when you just need to verify existence.

import importlib.util

module_name = 'numpy'

# ✅ Check existence without importing
spec = importlib.util.find_spec(module_name)

if spec is not None:
print(f"{module_name} is installed at: {spec.origin}")
else:
print(f"{module_name} is NOT installed.")

Output:

numpy is installed at: /usr/local/lib/python3.10/site-packages/numpy/__init__.py

Method 3: Checking via pip (Shell Command)

Sometimes you need to verify installation from the terminal or a shell script, rather than inside Python code.

Using pip show

pip show requests

If installed, it prints metadata (Name, Version, Location). If not, it prints nothing (or an error, depending on the pip version).

Using pip list (Grep)

pip list | grep requests

This lists all packages and filters for the specific name.

Running a One-Liner

You can run a Python one-liner from the shell to verify importability.

python -c "import requests; print('Installed')"

Conclusion

To check if a Python module is installed:

  1. Use try...except ImportError if you intend to use the module immediately.
  2. Use importlib.util.find_spec() if you need to check existence without loading the module into memory.
  3. Use pip show <package> for command-line verification.