Python
Module
Check
Import
Programming

How to check if a Python module exists without importing it

Codemia Knowledge Hub ·

Call importlib.util.find_spec("name"). It returns None if the module cannot be found and a ModuleSpec if it can, without running the module's code. To check whether a pip package is installed (by its distribution name), use importlib.metadata.version() instead.

Why check before importing

Avoiding side effects. Some modules run initialization code at import time, such as connecting to a database, configuring logging, or loading large data files. Checking first lets you decide whether to pay that cost.

Optional dependencies. Libraries like pandas, numpy, or redis may be optional for your application. A check lets you fall back to another implementation or show a helpful error message.

Circular imports. In large codebases, a top-level import can trigger a chain that circles back to the current module. Deferring the import and checking availability first can help you restructure the dependency.

importlib.util.find_spec()

This is the recommended approach for Python 3.4 and later. find_spec() searches for the module's spec without loading or executing the module.

python
1import importlib.util
2
3def module_exists(module_name):
4    """Return True if the module can be found, False otherwise."""
5    spec = importlib.util.find_spec(module_name)
6    return spec is not None
7
8# Check for common libraries
9print(module_exists("json"))      # True (stdlib)
10print(module_exists("pandas"))    # True if installed
11print(module_exists("fakepkg"))   # False

Dot notation works for submodules:

python
print(module_exists("os.path"))           # True
print(module_exists("email.mime.text"))   # True
print(module_exists("email.nonexistent")) # False

For a dotted name, find_spec() does import the parent package first (here os or email), and it raises ModuleNotFoundError instead of returning None if the parent itself is missing.

The returned ModuleSpec carries metadata such as the file location:

python
1spec = importlib.util.find_spec("json")
2if spec:
3    print(f"Module found at: {spec.origin}")
4    # Output: Module found at: /usr/lib/python3.11/json/__init__.py

pkgutil.find_loader() (deprecated)

Before find_spec() existed, pkgutil.find_loader() served the same purpose. It returns a loader object if the module exists and None if it does not.

python
1import pkgutil
2
3def module_exists(module_name):
4    """Check module existence using pkgutil."""
5    loader = pkgutil.find_loader(module_name)
6    return loader is not None
7
8print(module_exists("collections"))  # True
9print(module_exists("requests"))     # True if installed
10print(module_exists("boguslib"))     # False

pkgutil.find_loader() is deprecated as of Python 3.12. Use importlib.util.find_spec() in new code.

Checking an installed package with importlib.metadata

To check whether a package is installed, rather than importable, query its metadata. The distribution name can differ from the import name: the Pillow package is imported as PIL.

python
1# Python 3.8+
2from importlib.metadata import distributions, PackageNotFoundError
3import importlib.metadata
4
5def package_installed(package_name):
6    """Check if a distribution package is installed."""
7    try:
8        importlib.metadata.version(package_name)
9        return True
10    except PackageNotFoundError:
11        return False
12
13print(package_installed("requests"))  # True if installed
14print(package_installed("Pillow"))    # True if installed
15print(package_installed("PIL"))       # False (PIL is the import name, not the package name)

This checks installed distributions, not importable module names. Use it when you need to know that a pip-installed package is present.

Conditional import with a fallback

A common pattern combines the check with a conditional import and a fallback:

python
1import importlib.util
2
3def get_json_library():
4    """Use orjson if available, fall back to stdlib json."""
5    if importlib.util.find_spec("orjson") is not None:
6        import orjson
7        return orjson
8    else:
9        import json
10        return json
11
12json_lib = get_json_library()
13data = json_lib.loads('{"key": "value"}')
14print(data)

For repeated use, wrap the check in a helper that raises a clear error:

python
1import importlib.util
2
3def require_module(module_name, install_hint=None):
4    """Raise a clear error if a required module is missing."""
5    if importlib.util.find_spec(module_name) is None:
6        msg = f"Module '{module_name}' is required but not installed."
7        if install_hint:
8            msg += f" Install it with: pip install {install_hint}"
9        raise ImportError(msg)
10
11# Usage
12require_module("numpy", install_hint="numpy")
13import numpy as np

Methods compared

MethodChecksPython VersionStatus
importlib.util.find_spec()Importable modules3.4+Recommended
pkgutil.find_loader()Importable modules2.7+Deprecated 3.12
importlib.metadata.version()Installed packages3.8+Active

Cases where the check gives the wrong answer

Package name vs. module name. The name you pip install can differ from the import name. find_spec("PIL") finds Pillow, but importlib.metadata.version("PIL") does not. Use the method that matches what you are checking.

Wrong virtual environment. If the script runs in one Python environment and the module is installed in another, the check returns False. Run the check in the same environment as the code.

Namespace packages. find_spec() can return a spec for a namespace package even when no actual code is installed. To confirm the module has real code, also check that spec.origin is not None.

try: import x instead of a check. That works, but it runs module initialization and its side effects. If you need to avoid those, check first.


Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Basis Lab
No course covers this one yet

Basis Lab writes one for you from a sentence about what you want to be able to do, then teaches it and checks you understood. Your first course is free.

Build my course
Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms