Sub topic 14
Typing third-party libraries: stubs and py.typed
This chapter assumes you can run mypy and Pyright, read their errors, and edit pyproject.toml. Earlier chapters covered those skills. Your own code is now annotated, but it imports libraries you did not write. The checker needs type information for those libraries too, and where it finds that information decides whether your calls to them are checked or silently treated as Any.
Where a checker gets types for an import
When your code runs import requests, the checker must find type information for that module. Three sources exist:
- Inline types. The package contains annotations in its
.pyfiles and declares this with an empty marker file namedpy.typed. This is the standard from PEP 561. - Stub files. A
.pyifile holds only signatures, with no function bodies. Stubs are used when a library has no annotations or when annotating it is impractical. - Nothing. The checker finds the module but has no types for it, or cannot find the module at all.
A stub file looks like a Python file with every body replaced by .... The checker reads the .pyi instead of the .py whenever both exist, and the interpreter never loads the .pyi. Stubs therefore affect checking only and cannot change runtime behavior.
The resolution order
Both tools search several places in a fixed order. The exact order differs in details, but the outline is the same.
Typeshed is a shared repository of stubs. It covers the standard library and many popular third-party packages. Both checkers ship the standard-library part. Pyright also bundles the third-party part. mypy does not, so you install those stubs separately.
What the errors look like
Suppose you import requests in a project where mypy has no stubs for it:
import requests
response = requests.get("https://example.com", timeout=5)
print(response.status_code)mypy reports an error like this:
error: Library stubs not installed for "requests" [import-untyped]
note: Hint: "python3 -m pip install types-requests"A different message appears when the module is installed but has no stubs and no py.typed marker:
error: Skipping analyzing "somelib": module is installed, but missing library stubs or py.typed marker [import-untyped]A third form means mypy cannot find the module at all, which usually indicates a wrong environment or a typo:
error: Cannot find implementation or library stub for module named "somelib" [import-not-found]Treat these as three different problems. The first has a one-line fix. The second needs a decision. The third is an environment problem, so check which interpreter the checker runs under before changing any typing settings.
Installing stub packages
Stubs for third-party libraries are published on PyPI as separate packages. Typeshed's packages follow the naming pattern types-<project>:
python -m pip install types-requests types-PyYAMLmypy can also list and install the missing ones for you:
mypy --install-typesThis command asks for confirmation before it installs anything. In CI, use mypy --install-types --non-interactive src/, or better, add the types-* packages to your dev dependencies so builds are reproducible.
Some projects publish their own stubs as <project>-stubs packages. These work the same way and take priority over inline types in the library itself.
Pyright needs no install step for typeshed-covered libraries because it bundles those stubs. It reports reportMissingModuleSource as a warning when it finds a stub but cannot find the real package in your environment. That warning means the library is not installed, not that your types are wrong.
Checking whether a library ships its own types
Look for a py.typed file inside the installed package directory:
python -c "import attrs, pathlib; print(list(pathlib.Path(attrs.__file__).parent.glob('py.typed')))"A non-empty list means the package declares inline types. A package may mark itself as partial by putting the line partial\n in py.typed. In that case the checker falls back to other sources for the missing modules.
Writing a local stub
If no stubs exist, you can write a minimal one for just the parts you use. Say you depend on an untyped library called fastcolors. Create stubs/fastcolors.pyi:
def paint(text: str, color: str = ...) -> str: ...
class Palette:
names: list[str]
def __init__(self, names: list[str] | None = ...) -> None: ...
def lookup(self, name: str) -> tuple[int, int, int]: ...In a stub, = ... marks a parameter default whose value does not matter for typing. Then point each checker at the directory:
[tool.mypy]
mypy_path = "stubs"
[tool.pyright]
stubPath = "stubs"Pyright's default stubPath is typings, so you can also leave that setting out and use a typings/ directory. You do not have to write the whole library. A stub covering the functions you call turns Any into checked types for those calls. Anything the stub omits is reported as an error, so grow the stub as you use more of the library.
Both ecosystems provide generators for a first draft. stubgen -p fastcolors -o stubs comes with mypy, and pyright --createstub fastcolors comes with Pyright. Generated stubs are often full of Any, so tighten the signatures you rely on.
Silencing a library without hiding everything
When you cannot fix the types yet, limit the damage to the specific module. In mypy, use a per-module override:
[[tool.mypy.overrides]]
module = ["somelib.*", "otherlib"]
ignore_missing_imports = trueThis turns imports from those modules into Any. Avoid setting ignore_missing_imports = true globally. A global setting also hides typos in module names and missing packages in your environment, which are real bugs.
In Pyright, the matching knobs are rule settings:
[tool.pyright]
reportMissingTypeStubs = false
reportMissingModuleSource = "none"Pyright also infers types from library source when no stubs exist (useLibraryCodeForTypes, on by default). Those inferred types can be incomplete or wrong, because the checker is guessing from unannotated code.
Differences between the two checkers
| Behavior | mypy | Pyright |
|---|---|---|
| Third-party typeshed stubs | Not bundled; install `types-*` packages | Bundled with the tool |
| Untyped installed package | `import-untyped` error | Infers from source by default |
| Local stub directory setting | `mypy_path` | `stubPath` (default `typings`) |
| Per-module silencing | `[[tool.mypy.overrides]]` | Rule settings or `# pyright: ignore` |
| Stub generator | `stubgen` | `pyright --createstub` |
A practical consequence follows from the table. A project can pass Pyright in your editor and fail mypy in CI, with the only cause being that types-requests is installed in one environment and not the other. Put the stub packages in the same dev dependency group that installs the checkers.
Common mistakes
- Setting
ignore_missing_imports = truefor the whole project to make the first run pass, then never narrowing it. - Installing stubs into a different virtual environment from the one the checker uses. mypy has
--python-executableand Pyright hasvenvPathandvenvfor pointing at the right environment. - Expecting
types-*packages to do anything at runtime. They contain only.pyifiles. - Leaving a local stub in place after the library gains real types. A local stub takes priority and can hide the library's own annotations.
Exercise
Your CI run of mypy fails with Library stubs not installed for "yaml", but Pyright in your editor shows no problem for import yaml. Why do the tools disagree, what is the best fix, and why is ignore_missing_imports = true for the whole project a poor choice?
Show answer
Pyright bundles the third-party typeshed stubs, including those for PyYAML, so it finds types without any install. mypy does not bundle them, so it reports the missing stubs. The best fix is to add types-PyYAML to the dev dependencies that install the checkers, so every environment has the same stubs. A global ignore_missing_imports = true would also turn mistyped module names and uninstalled packages into silent Any, which hides real errors. If silencing is needed at all, apply it with a [[tool.mypy.overrides]] entry for specific modules.