Type Hints & Annotations
mypy
Static type checking with mypy — configuring, running, understanding errors, and integrating type checking into your development workflow.
Interview: Professional code quality — shows commitment to reliable, maintainable codebases.
mypy is the standard static type checker for Python. It analyzes your code without running it, catching type errors before they reach production. Combined with IDE integration, mypy catches bugs that would otherwise slip through testing.
Getting Started
- Install:
pip install mypy - Run:
mypy mymodule.pyormypy --strict mypackage/ - Configuration:
mypy.inior[mypy]section inpyproject.toml - IDE integration: most editors show mypy errors inline
Strictness Levels
- Default: Only checks annotated code, ignores unannotated functions
--disallow-untyped-defs— require all functions to have annotations--strict— all checks enabled, most rigorous- Use
# type: ignoresparingly to suppress false positives
Common mypy Errors
Incompatible return type— function returns wrong typeArgument N to "func" has incompatible type— wrong argument typeItem "None" of "Optional[X]" has no attribute— forgot to check for NoneMissing return statement— not all code paths return a value
Interview Insight
Know how to run mypy and interpret its errors. In interviews, mention that mypy catches type errors statically (without running code) and that --strict mode enforces full type coverage.
Use Cases
CI/CD pipeline — run mypy before merging pull requests
Legacy code migration — gradually add types and check with mypy
Library development — py.typed marker for typed library distribution
Bug prevention — catching type errors before runtime
Code review — mypy errors are objective, not subjective style preferences
Common Mistakes
Not running mypy at all — type hints without checking are just documentation
Overusing type: ignore — fix the root cause instead of suppressing errors
Starting with --strict on a legacy codebase — use gradual typing instead
Not configuring mypy.ini — default settings miss many useful checks
Forgetting py.typed marker — library consumers won't see your type hints