DEV Community

Alex Chen
Alex Chen

Posted on

Quick Tip: Fix "ModuleNotFoundError" in 10 Seconds with importlib.metadata

Quick Tip

You pip install a package, the install says "Successfully installed", and Python still throws ModuleNotFoundError. Nine times out of ten the distribution name ≠ the import name. Instead of guessing, ask the environment directly:

from importlib.metadata import distributions

# Every installed dist: name it answers to + top-level modules it provides
for d in distributions():
    name = d.metadata["Name"]
    tops = (d.read_text("top_level.txt") or "").split()
    print(f"{name:30s} -> {', '.join(tops) or '?'}")
Enter fullscreen mode Exit fullscreen mode

One run and you see the classic offenders:

scikit-learn                   -> sklearn
PyYAML                         -> yaml
opencv-python                  -> cv2
beautifulsoup4                 -> bs4
Pillow                         -> PIL
Enter fullscreen mode Exit fullscreen mode

Bonus one-liner when you need to check if a coworker's venv matches yours:

from importlib.metadata import version
print(version("numpy"))   # '2.1.3' — no pip freeze round-trip needed
Enter fullscreen mode Exit fullscreen mode

No pip list | grep archaeology. Works on Python 3.10+ out of the box.

I draft little diagnostic snippets like this with MonkeyCode (free, open-source): https://ly.cyberserval.tech/iIETXiF

Which name/import mismatch has bitten you the most? Mine is still opencv-pythoncv2.

Top comments (0)