Core processing logic
DevOps & Tooling / Knowledge library
mypy
gradual typing annotations protocols and type narrowing
Why learn mypy?
Useful for catching interface mismatches before runtime. Unchecked dynamic code and Any values can leave gaps, and annotations do not validate incoming data.
Where it came from
mypy analyzes Python type annotations to find inconsistencies without executing the program. Its gradual typing model supports incremental adoption.
Build your understanding
Work through these exercises in order. Try the task before opening a reference.
- Annotate a function's inputs and output.
- Introduce and fix a deliberate type mismatch.
- Narrow an optional value before use.
- Define a protocol for a dependency.
- Inspect how Any or missing annotations reduce coverage.
Documentation and sources
- Official project documentation (mypy.readthedocs.io)
Catalog research notes
- Research snapshot: September 9, 2026. This entry summarizes the linked primary documentation; it does not assert a latest release version.
Connect the ideas
Built on
Explore next
Real World Example
Protocol-Based Plugin Architecture for Data Ingestion
Data engineering teams building modular ingestion pipelines that must support diverse, third-party data sources without tight coupling.
The business problem
Runtime errors occur when ingestion modules expect specific attributes from dynamic data objects, leading to attribute errors during production execution.
How this topic solves it
Mypy Protocols enable structural subtyping, allowing developers to define an interface based on required attributes rather than inheritance, while type narrowing safely confirms object capabilities at runtime.
- Define a Protocol class specifying the required methods or attributes for a data source.
- Annotate ingestion functions to accept the Protocol type instead of concrete classes.
- Implement type narrowing using isinstance() or type guards to verify object structure before access.
- Run mypy to statically validate that all passed objects satisfy the Protocol requirements.
Shows how ingestion logic validates data sources via Protocols.
Interface definition
Concrete data source
Concrete data source
- IngestionEngine → depends on → DataSourceProtocol
- ExternalAPI → satisfies → DataSourceProtocol
- DatabaseSource → satisfies → DataSourceProtocol
Expected business outcome
Increased system reliability through compile-time detection of missing interface implementations, reducing runtime attribute errors.
Limitations and checks
Protocols rely on structural compatibility, which can lead to false positives if two objects share the same attribute names but have different semantic meanings; verify with runtime checks.