DEV Community

Andrew
Andrew

Posted on

mypy Cannot Find Implementation or Library Stub for Module

Your editor shows no squiggles, but the CI job fails with:

services/api/src/api/routes.py:3: error: Cannot find implementation or library stub for module named "shared.models"
Found 1 error in 1 file (checked 12 source files)
Enter fullscreen mode Exit fullscreen mode

Pylance resolves shared.models without complaint, so the code looks fine. The mismatch is not a bug in either tool. mypy and Pylance read different configuration files, build different module search paths, and may inspect different interpreters. This article shows why the error appears, how to configure both checkers for a src layout and local packages, and how to run them in CI so they finally agree.

Table of Contents

Why Pylance Is Clean While mypy Fails

The message is literal: when mypy says it cannot find implementation or library stub for module named shared.models, it could not find the module at all, whether or not it contains type hints. The mypy documentation on running mypy and managing imports describes this as distinct from "Library stubs not installed" and "Skipping analyzing": those mean the module was found but its type information was missing, whereas this error means the module itself never entered mypy's search path.

In the example above, the repository looks like this:

repo/
├── pyproject.toml
├── pyrightconfig.json
├── packages/
│   └── shared/
│       └── src/shared/models.py
└── services/
    └── api/
        └── src/api/routes.py
Enter fullscreen mode Exit fullscreen mode

routes.py contains from shared.models import User. Pylance finds it because pyrightconfig.json lists packages/shared/src under extraPaths. mypy fails because pyproject.toml only tells it to check services/api/src, so the directory containing the shared package is never added to its search path.

A clean editor therefore proves only that one analyzer, with one configuration, can resolve the import. It says nothing about how mypy is invoked in CI, which is often from a different directory, in a different virtual environment, with a different config file.

Two Type Checkers, Two Different Search Paths

mypy builds its own search path rather than reusing whatever your program does at runtime. That path is computed from the MYPYPATH environment variable, the mypy_path config option, the directories containing the source files passed on the command line, the installed packages marked as safe for type checking under PEP 561, and the bundled typeshed stubs.

Pyright, the engine behind Pylance, resolves an absolute import in a different order: custom stubs from stubPath, code in the workspace (the execution environment root, then extraPaths, then a local src directory when no execution environment is configured), installed packages and their stubs, standard-library typeshed stubs, and third-party typeshed stubs. Pyright's import resolution documentation lists that sequence in full.

Two practical differences follow:

  • src is not magic for mypy. Pyright checks a local src directory automatically when no execution environment is configured, which is why a src layout can work in the editor with no path setting at all. mypy has no equivalent automatic step; if the import root is not on its search path, the import fails.
  • The configuration files are separate. Pylance reads VS Code settings and pyrightconfig.json or [tool.pyright]. mypy reads mypy.ini, .mypy.ini, [tool.mypy] in pyproject.toml, or setup.cfg. Editing one does nothing for the other.

For the editor side of that lookup order, this walkthrough of Pylance's import resolution model maps each search stage to the setting that controls it, including the reportMissingImports diagnostic itself. The rest of this article handles the mypy side and the parity between them.

Configure mypy for a src Layout

Put the paths in the same repository-level pyproject.toml that your team already shares:

[tool.mypy]
python_version = "3.12"
files = ["services/api/src", "packages/shared/src"]
mypy_path = "$MYPY_CONFIG_FILE_DIR/packages/shared/src,$MYPY_CONFIG_FILE_DIR/services/api/src"
explicit_package_bases = true
namespace_packages = true
warn_unused_configs = true
Enter fullscreen mode Exit fullscreen mode

Three details matter here:

  1. mypy_path entries are import roots. Point at the directory that contains the top-level package, so packages/shared/src for import shared, not packages/shared/src/shared.
  2. Relative paths resolve from the working directory, not the config file. The mypy configuration reference recommends $MYPY_CONFIG_FILE_DIR to make paths survive being run from a different directory, which is exactly what happens when CI runs mypy from the repository root or a subdirectory.
  3. explicit_package_bases handles packages without __init__.py. With it enabled, mypy uses the nearest parent directory that is on mypy_path, in MYPYPATH, or is the current directory to derive the fully qualified module name. That is what lets packages/shared/src/shared/models.py be treated as shared.models even at the top of a PEP 420 namespace package.

Including packages/shared/src in files also puts that root on mypy's search path for this particular run, but an explicit mypy_path survives narrower invocations such as mypy services/api/src and gives you a line to compare directly with extraPaths.

MYPYPATH is the environment-variable equivalent of mypy_path. If your CI sets it instead, export the same absolute paths before running mypy: export MYPYPATH="$PWD/packages/shared/src". Do not point it at a stub-only package, because PEP 561 stub packages must be installed rather than added to the path.

If you run mypy without files, remember that passing a directory such as mypy services/api/src adds that directory to the search path, not every source root in the repository. The explicit config above avoids relying on the invocation to supply the roots.

Mirror the Import Roots in pyrightconfig.json

Pyright's configuration reference defines extraPaths as additional module search paths, and executionEnvironments as a list of roots with their own settings. Keep a checked-in pyrightconfig.json rather than relying on a teammate's VS Code settings:

{
    "include": ["services/api/src", "packages/shared/src"],
    "extraPaths": ["packages/shared/src", "services/api/src"],
    "pythonVersion": "3.12",
    "typeCheckingMode": "standard"
}
Enter fullscreen mode Exit fullscreen mode

This file now carries the same two import roots as mypy_path, so both analyzers see shared and api. The pythonVersion entry pins the language level independently of whichever interpreter happens to be selected.

For a monorepo where packages should be analyzed with different roots or versions, use execution environments instead of one flat list:

{
    "executionEnvironments": [
        {
            "root": "services/api",
            "extraPaths": ["packages/shared/src"],
            "pythonVersion": "3.12"
        },
        {
            "root": "packages/shared",
            "extraPaths": [],
            "pythonVersion": "3.12"
        }
    ]
}
Enter fullscreen mode Exit fullscreen mode

Each source file is matched against the roots from top to bottom, so the first matching environment supplies the settings for that file.

Use the Same Interpreter in Both Tools

A matching path configuration still fails if mypy inspects a different environment from the one where your dependencies are installed. mypy uses the interpreter that runs it to find PEP 561 packages by default, and the python_executable config option or --python-executable flag points it at another environment.

The simplest habit is to invoke mypy as a module inside the target environment:

python -m mypy
Enter fullscreen mode Exit fullscreen mode

That guarantees the mypy process and the installed packages come from the same interpreter. If mypy is installed globally but your project lives in .venv, either install mypy in the venv or tell it where to look:

python -m mypy --python-executable .venv/bin/python
Enter fullscreen mode Exit fullscreen mode

or, in pyproject.toml:

[tool.mypy]
python_executable = ".venv/bin/python"
Enter fullscreen mode Exit fullscreen mode

Pylance follows the interpreter selected for the workspace through the Python extension or Python Environments. The Pylance guide to choosing a Python environment warns that a wrong interpreter makes almost every diagnostic misleading: third-party imports look broken, standard-library types look wrong, and pip install appears to do nothing because it targeted another environment. If Pylance is clean and mypy is not, confirm the two are looking at the same site-packages before changing path settings.

For the Pyright CLI, --pythonpath is the equivalent knob and is recommended over --venvpath in most cases, according to Pyright's command-line reference:

pyright --pythonpath .venv/bin/python
Enter fullscreen mode Exit fullscreen mode

Note that venvPath and venv in pyrightconfig.json are ignored by Pylance, which always uses the VS Code interpreter selection. In CI there is no Pylance, so pass --pythonpath explicitly or rely on the interpreter that invoked the CLI.

Put Both Checks in One CI Job

The most reliable setup runs both checkers in the same job, in the same environment, from the same repository root. The Pylance CI type-checking guide notes three details that catch teams repeatedly:

  • The Pyright CLI never reads VS Code settings.json. Any extraPaths or diagnostic settings that exist only in the editor must be copied into pyrightconfig.json or [tool.pyright].
  • Pylance bundles type stubs for some popular packages, while the Pyright CLI does not. An import can therefore resolve in the editor and fail in CI even with identical path settings; install types-* packages where needed.
  • Pyright needs the project's dependencies installed in site-packages before it can resolve third-party imports.

A compact GitHub Actions job puts those rules into practice:

name: type-check
on: [push, pull_request]
jobs:
  types:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with:
          python-version: "3.12"
      - run: python -m pip install -e ./packages/shared -e "./services/api[dev]" mypy
      - run: python -m mypy
      - run: npx --yes pyright@1.1.400 --pythonpath "$(python -c 'import sys; print(sys.executable)')"
Enter fullscreen mode Exit fullscreen mode

Pin the Pyright version rather than using the latest release, so an upstream change cannot break the build overnight. If your packages use editable installs, configure setuptools to write path-based .pth files (--config-settings editable_mode=compat) or use a backend such as uv_build or Hatchling that does so by default; import-hook editable installs are invisible to Pyright.

If your workflow installs dependencies with pip install -e ., keep the mypy_path and extraPaths entries anyway. Installed packages and explicit source roots solve different problems: an editable install can silently disappear after a packaging change, while the path settings keep the source layout analysable either way.

Which Setting Fixes Which Symptom?

Use the diagnostic and the scope of the failure to pick the knob:

Symptom mypy Pylance / Pyright
A first-party package under another src root is unresolved Add its directory to mypy_path (or MYPYPATH) Add it to extraPaths or an execution environment
Quick checks pass, but mypy . from the repo root fails Set files and mypy_path in pyproject.toml; use $MYPY_CONFIG_FILE_DIR Check include and extraPaths in pyrightconfig.json
Third-party imports fail only in CI python -m mypy in the project environment, or --python-executable Install dependencies first; pass --pythonpath to the CLI
Editor clean, CI mypy failing Copy the editor's import roots into mypy_path; check the CI working directory Copy VS Code paths into pyrightconfig.json, since the CLI ignores settings.json
"Library stubs not installed for X" Install the types-* stub package or add it to dev dependencies Enable reportMissingTypeStubs only if you want the warning
"Cannot find implementation or library stub" persists Fix the path or environment; avoid --ignore-missing-imports as a first move Confirm reportMissingImports is not being masked by bundled stubs

The last row is the important one. --ignore-missing-imports and per-module ignore_missing_imports turn the module into Any, so the error disappears while mypy loses the ability to check everything that touches it. Treat suppression as a deliberate choice for untyped third-party libraries, not as a fix for a first-party import.

Conclusion

mypy and Pylance disagree because they are configured separately and resolve imports differently. Pylance searches workspace roots, extraPaths, and a local src directory, then installed packages and bundled stubs. mypy searches MYPYPATH, mypy_path, the directories of the sources you pass it, and PEP 561 packages, with some extra logic from explicit_package_bases for namespace packages.

Make the two configurations mirror each other: one set of import roots in mypy_path, the same set in extraPaths or executionEnvironments, one pinned Python version, and the same interpreter for both commands. Run python -m mypy and pyright --pythonpath in the same CI job, install dependencies first, and pin the Pyright version. Once both analyzers see the same modules, a clean editor and a green CI run finally mean the same thing.

Top comments (0)