Sub topic 9
Shipping type hints with py.typed
Your greeter library already has type annotations. This chapter covers how to make type checkers use them in the projects that install your package. It assumes you can read basic annotations, have built a wheel with python -m build (see the earlier chapters), and have used a virtual environment.
Why annotations are not enough
Annotations in your source are invisible to your users' type checkers by default. When mypy or Pyright finds an installed package, it asks whether the author promised the package is typed. Without that promise, the checker treats the package as untyped and ignores its annotations. mypy reports:
error: Skipping analyzing "greeter": module is installed, but missing library stubs or py.typed markerThe promise is a marker file named py.typed. It is defined by PEP 561, the standard for distributing type information. The file is usually empty. Its presence tells checkers to trust the inline annotations in the package.
Adding the marker
Put an empty py.typed file next to __init__.py in the top-level package. The src layout from the first chapter already has a slot for it:
src/
└── greeter/
├── __init__.py
├── cli.py
└── py.typedOne marker at the top level covers every subpackage below it. You do not need a copy in each directory.
Creating the file is not enough, because the build backend must also copy it into the wheel. Setuptools only packages .py files by default, plus data files you declare. Declare the marker explicitly in pyproject.toml:
[tool.setuptools.package-data]
greeter = ["py.typed"]You can also add a trove classifier so PyPI shows that the package is typed:
classifiers = [
"Programming Language :: Python :: 3",
"Typing :: Typed",
]The classifier is only a label for people browsing PyPI. Type checkers never read it, so it cannot replace the file.
Inline types, stub packages, and the alternatives
PEP 561 describes three ways to ship type information. This chapter uses the first, which is the best choice for a library you write yourself.
| Approach | How it works | Use it when |
|---|---|---|
| Inline types with `py.typed` | Annotations live in the `.py` files. The marker enables them. | You own the code and can annotate it. |
| Stub files in the package | `.pyi` files sit beside the `.py` files. The marker is still required. | You want to keep types out of the source, or the code is dynamic enough that annotations are awkward. |
| Separate stub package | A distribution named `greeter-stubs` contains only `.pyi` files. | You are typing someone else's library. |
A package can also be partly typed. If you add partial on its own line inside py.typed, checkers fall back to other sources for modules you have not annotated. Most libraries don't need this. Annotate everything public and leave the file empty.
How a checker decides
The diagram shows the lookup a checker performs for each import. The marker is the deciding step for an installed package.
Making the public API checkable
Strict checkers apply rules that affect how you write __init__.py. mypy with --strict turns on --no-implicit-reexport. Under that rule, a name you only import inside __init__.py is not part of your public API unless you mark it. Our greet function is defined directly in __init__.py, so it is exported. If you later move it into a module, re-export it in one of these ways:
# src/greeter/__init__.py
from importlib.metadata import version
from greeter.core import greet as greet
__all__ = ["__version__", "greet"]
__version__ = version("greeter")Both forms work. import x as x and an __all__ entry each tell checkers the name is public. Pick one style and use it consistently.
Next, check your support range. The project declares requires-python = ">=3.9", so the annotations must be valid on 3.9. Built-in generics such as list[str] work on 3.9. The str | None union syntax does not work at runtime before 3.10. If you want that syntax on 3.9, add from __future__ import annotations at the top of the module. That makes annotations lazy strings, so they are never evaluated at runtime. The exception is code that inspects annotations at runtime, such as pydantic models or dataclass tooling. Test that code on your oldest supported version.
Types from your own dependencies matter too. If a public signature mentions a type from another library, users need that library installed to get meaningful checking. Declare it as a normal runtime dependency. If it ships separate stubs, such as types-requests, do not make those a requirement of your package. Document them or put them in an extra.
Typing the console script
The main function in cli.py returns None and takes no arguments, so it is already fully annotated. Checkers handle entry points like any other function. Since sys.argv is a list[str], the line name = sys.argv[1] if len(sys.argv) > 1 else "world" infers str with no extra annotation.
Checking your own code in CI
The marker is a promise. Honor it by running a checker over the source on every change:
python -m pip install mypy
python -m mypy --strict src/greeterStart with --strict on a new library. Adding it later to a codebase with many untyped functions is much harder. If your tests are part of the project, check them too, but treat that as separate from verifying the package.
Verifying the shipped package
A passing check on the source tree proves little about the package users install. The source tree has the marker even when the wheel does not. Check the built artifacts in two steps.
First, confirm the marker is inside both artifacts:
python -m build
python -m zipfile -l dist/greeter-0.1.0-py3-none-any.whl | grep py.typed
tar tzf dist/greeter-0.1.0.tar.gz | grep py.typedEach command should print one line that ends in greeter/py.typed. If the wheel line is missing, the package-data setting is wrong.
Second, check from the consumer's side. Install the wheel into a fresh virtual environment and run a checker against a small file that uses your library, with a deliberate mistake:
# consumer.py
from greeter import greet
message: int = greet("Ada")python -m venv /tmp/typed-check
/tmp/typed-check/bin/pip install dist/greeter-0.1.0-py3-none-any.whl mypy
/tmp/typed-check/bin/mypy consumer.pyWith the marker present, mypy reports an incompatible assignment: greet returns str but the variable is declared int. That error shows the checker is reading your annotations. If the marker is missing, you get the "missing library stubs or py.typed marker" message instead. This consumer test costs little and catches the most common packaging mistake.
Common failures
- The marker is in the repository but not in the wheel. Packaging config does not include it. Add the
package-dataentry and rebuild. - The marker is in the wrong directory. It must be inside the importable package (
src/greeter/), not at the repository root or insrc/. - Everything resolves to
Any. A function without annotations is treated as returningAny. Strict mode on your source catches these. - Names are missing under strict checking. An implicit re-export from
__init__.pyneeds__all__or theasform. - Runtime errors on older Python. A newer annotation syntax is used without the
__future__import, on a version older than the syntax allows.
Exercise
You added src/greeter/py.typed and published a wheel, but users still see "missing library stubs or py.typed marker". The file exists in your repository. Which two checks find the cause, and what is the likely fix?
Show answer
List the wheel contents (python -m zipfile -l on the .whl file) and look for greeter/py.typed, then install the wheel in a clean virtual environment and run mypy on a small consumer file. The marker is almost certainly missing from the wheel because the build backend did not include it. Add [tool.setuptools.package-data] with greeter = ["py.typed"] to pyproject.toml, rebuild, and release a new version.
Exercise
Why is it not enough to run mypy on src/greeter in CI to prove your package is correctly typed for users?
Show answer
That check reads the source tree, where py.typed exists whether or not the build packaged it. It cannot detect a wheel that lacks the marker. You also need to inspect the built artifacts and run a checker from a clean environment against the installed wheel, as a user would.