Runtime checks: Enforcing types while the program runs (e.g., typeguard, beartype).
CI gates: Integrating these checks into a Continuous Integration pipeline.
This request implies the user wants to move from "casual" Python usage to a more robust, production-grade setup where types are enforced rigorously, similar to languages like TypeScript or Java, but within Python's ecosystem.
Plan:
Introduction: Acknowledge Python's dynamic nature vs. the benefits of type safety (maintainability, refactoring, IDE support).
Static Analysis (The Foundation):
Compare mypy (the OG) vs. pyright (fast, Microsoft, Pylance). Recommend pyright for speed but acknowledge mypy's plugin ecosystem.
Configuration (pyproject.toml or mypy.ini).
Strictness settings (strict mode).
Advanced Typing Features (Protocols):
Explain Nominal vs. Structural subtyping.
Show typing.Protocol example (Duck typing with safety).
@runtime_checkable.
Runtime Enforcement (Bridging the Gap):
Static analysis ignores dynamic inputs (JSON, user input).
Tools: typeguard, beartype, pydantic (validation vs. pure typing).
Example using beartype for decoration.
CI/CD Integration (The Gatekeeper):
Pre-commit hooks (local gate).
GitHub Actions / GitLab CI (remote gate).
Failing the build on type errors.
Architecture/Best Practices:
Single-sourcing types (don't duplicate).
TypedDict for JSON.
The "Pydantic" pattern for API boundaries.
Summary/Checklist: A quick "how to start" guide.
Drafting content - Section by Section:
Static Checkers: I need to highlight that mypy is the standard, but pyright is often preferred now for performance and feature support (e.g., newer PEPs). I should recommend putting config in pyproject.toml.
Protocols: This is crucial for "Pythonic" type safety. Instead of forcing inheritance (nominal), use structural subtyping. Example: A Drawable protocol.
Runtime: This is controversial. Python developers often resist runtime checks due to overhead. I need to mention beartype (fast) or typeguard. Crucially, distinguish between validation (Pydantic) and type checking (Beartype).
CI: Needs concrete YAML examples or steps. pre-commit is essential for developer experience (DX).
Refining the "Push" aspect:
The user used the word "Push". This implies aggressive adoption.
Strict Mode: Enable strict = true.
No Any: disallow untyped defs.
Test Types: Run mypy on test files too.
Self-Correction during drafting:
Initial thought: Focus heavily on Pydantic.
Correction: Pydantic is data validation. While it uses type hints, the prompt specifically asks about type safety (protocols, mypy). I should mention Pydantic as the boundary guard, but keep focus on the core typing tools.
Structure:
The Toolchain: Pyright vs Mypy.
Structural Typing: Protocols.
The Runtime Gap: Beartype/Typeguard.
The Workflow: CI & Pre-commit.
Configuration Example: A solid pyproject.toml snippet.
Let's write the response following this structure. I will ensure the tone is professional and technical.
Pushing type safety in Python requires a multi-layered approach. You cannot rely solely on static analysis (mypy/pyright) because Python remains a dynamic language at runtime. To achieve "rigid" safety, you must bridge the gap between static hints and runtime behavior, and enforce it all via CI.
Here is a high-level guide to implementing strict type safety across your stack.
1. Static Analysis: The Foundation
The first layer is the linter. You should move away from the basic mypy default configuration and embrace "Strict Mode."
Mypy vs. Pyright
Mypy: The standard. It is stricter and more pedantic. Best for pure Python codebases ensuring backward compatibility.
Pyright (Pylance): Faster, used by VS Code. It handles complex type inference better than Mypy and supports newer PEPs faster.
Recommendation: Run both locally or in CI. Mypy for strictness, Pyright for speed and IDE integration.
The "Strict" Configuration
Do not enable flags one by one. Use the strict preset and disable only what is absolutely necessary.
pyproject.toml (Mypy):
toml
[tool.mypy]
python_version = "3.11"
strict = true
# Optional: Be strict about untyped dependencies
ignore_missing_imports = false
# Ensure all functions are typed
disallow_untyped_defs = true
Stop relying on inheritance (Nominal Subtyping) for everything. Python favors "Duck Typing." Protocols allow you to type-check duck typing statically.
If Class A walks like a duck and Class B walks like a duck, but they don't inherit from a Duck base class, standard type checkers fail. Protocols solve this.
Example:
python
from typing import Protocol
class Renderable(Protocol):
# Any object with a 'render' method matching this signature
# is implicitly a Renderable.
def render(self) -> str: ...
def draw(widget: Renderable) -> None:
print(widget.render())
class Button:
def render(self) -> str: return "Button"
class User:
def render(self) -> str: return "User Profile"
# This passes static analysis because Button implements the Protocol implicitly
draw(Button())
Why this pushes safety: It decouples interfaces from implementations, allowing you to type-check third-party libraries or disjoint objects without forcing a rigid inheritance hierarchy.
3. Runtime Enforcement: Bridging the Gap
Static types vanish at runtime. If your code receives a JSON payload from an API, mypy thinks it's a dict, but it could contain anything. You need Runtime Type Checking.
Tier 1: Boundary Checking (Pydantic)
Use Pydantic for all "boundary" data (API inputs, DB models, config files). It validates data against type hints at the moment of instantiation.
python
from pydantic import BaseModel, ValidationError
class User(BaseModel):
id: int
name: str
tags: list[str]
# Safe instantiation
user = User(id=1, name="Alice", tags=["admin"])
# Raises ValidationError at runtime (catching unsafe data)
# user = User(id="not_an_int", name="Bob")
Tier 2: Function Contracts (Typeguard / Beartype)
If you need to enforce type hints inside function logic (e.g., ensuring a callback returns what it promises), use libraries like Typeguard or Beartype.
Beartype is particularly powerful as it performs O(1) non-blocking checks.
python
from beartype import beartype
@beartype
def process_data(data: list[int]) -> int:
return sum(data)
# This will raise a TypeError at runtime immediately
# process_data([1, 2, "three"])
4. CI Gates: The Enforcer
If it's not in CI, it doesn't exist. Your pipeline must fail on type errors.
Step 1: Pre-commit (Local Gate)
Use pre-commit to run type checkers before the code is even committed.