Distribute Type Information with py.typed and Stubs
Core idea
A package with inline annotations can advertise typing support by shipping a py.typed marker in the package. A .pyi stub declares a static interface separately from runtime implementation; it can also be shipped in a stub-only distribution following typing rules. A checker consumes type information; the marker does not enforce runtime types.
from pathlib import Pathfrom tempfile import TemporaryDirectorywith TemporaryDirectory() as tmp: package = Path(tmp) / 'parcel' package.mkdir() (package / '__init__.py').write_text('def count() -> int: return 2\n', encoding='utf-8') (package / 'py.typed').touch() print((package / 'py.typed').is_file())The empty marker exists in the source package; artifact inclusion must still be verified.
Expected output:
TrueWrite an interface stub
import astsource = 'def count(label: str) -> int: ...'node = ast.parse(source).body[0]print(node.name, ast.unparse(node.returns))The stub syntax describes the interface; this AST inspection does not run a type checker.
Expected output:
count intCommon mistake
Do not ship a stub that contradicts the runtime implementation. Verify the marker and stubs in the built wheel and test an installed consumer using a pinned checker.
Practice
Build a package with inline annotations and py.typed; test a correct call and a deliberately wrong call with a checker in a separate environment. Record version and diagnostics.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Typed packages and stubs
Check your understanding of typed packages and stubs.
What is printed?
import astprint(ast.parse("def f() -> int: ...").body[0].name)What is printed?
def f(x: int) -> int: return xprint(f("text"))What file signals inline typing support?
Does an AST parse verify type compatibility?