patternpythonModeratepending
Python type hints and mypy — gradual typing for existing codebases
Viewed 0 times
type hintsmypypyrightProtocolTypedDictgradual typingOptional
terminallinuxmacos
Problem
Large Python codebase has no type hints. Runtime type errors are caught only in production. Need to add typing gradually without rewriting everything at once.
Solution
(1) Start with mypy in permissive mode: mypy --ignore-missing-imports --allow-untyped-defs. (2) Type the most-changed and most-imported files first. (3) Use reveal_type() during development to see inferred types. (4) Common types: list[str], dict[str, int], Optional[str] (or str | None in 3.10+), Union[str, int]. (5) Function signatures: def process(items: list[Item], *, limit: int = 10) -> Result:. (6) Use Protocol for structural typing (duck typing with type safety). (7) Use TypedDict for dictionary shapes. (8) Stub files (.pyi) for third-party libraries without types. (9) CI: run mypy on typed files only, expand gradually. (10) Use pyright for faster checking and better IDE integration.
Why
Type hints catch bugs at development time, enable IDE autocomplete, and serve as living documentation. Gradual typing means you can add types incrementally without stopping all development.
Revisions (0)
No revisions yet.