We are going to discuss how to enhance type safety in Python using various tools and practices.
Steps:
Use a static type checker (mypy or pyright) in your development workflow and CI.
Define clear interfaces using typing.Protocol for structural subtyping (duck typing).
Perform runtime checks for critical code paths (using typeguard or custom checks) to ensure type safety at runtime.
Set up CI gates that run the static type checker and runtime checks (if any) and fail on type errors.
Let's break down each step:
Static Type Checker:
Choose either mypy or pyright (or both, but typically one is enough). They have different strengths but both are widely used.
Configure the type checker to be strict (e.g., --strict for mypy) or adjust the configuration to your project's needs.
Integrate the type checker in your pre-commit hooks and CI pipeline.
Protocols:
Use Protocol from typing (or typing_extensions for older Python versions) to define interfaces that classes should adhere to without requiring inheritance.
This is particularly useful for defining expected behavior (methods, properties) for dependency injection or for clarifying expected types in function arguments.
Runtime Checks:
While static type checking is great, it doesn't run at runtime. For critical sections (like API endpoints, data validation, etc.), you might want to add runtime type checks.
You can use the typeguard library to decorate functions and check that the arguments and return values match the type hints at runtime.
Alternatively, you can write custom validation (e.g., using pydantic for data validation) which also enforces types.
CI Gates:
Set up your CI (GitHub Actions, GitLab CI, etc.) to run the static type checker and any runtime checks (if applicable) and fail the build if there are type errors.
Example project structure:
Let's assume we have a simple project with a module that defines a protocol and a class that implements it, and a function that uses the protocol.
File: my_module.py
python
from typing import Protocol, runtime_checkable
@runtime_checkable
class MyProtocol(Protocol):
def required_method(self) -> int:
...
class MyClass:
def required_method(self) -> int:
return 42
def use_protocol(obj: MyProtocol) -> int:
return obj.required_method()
# This will pass static type checking because MyClass has the required method.
# Also, because we used @runtime_checkable, we can do runtime checks with isinstance.
Now, let's set up:
Step 1: Install and run mypy (or pyright)
For mypy:
Install: pip install mypy
Run: mypy --strict my_module.py
For pyright:
Install: pip install pyright or use the one built into VS Code.
Run: pyright my_module.py
Step 2: We already used a Protocol.
Step 3: Let's add runtime checks using typeguard.
Install: pip install typeguard
Decorate the function use_protocol with @typechecked from typeguard.
But note: typeguard works by checking the types at runtime when the function is called. It's a decorator that does the checking.
However, note that typeguard might not work perfectly with all type hints (like Protocol without @runtime_checkable). But with @runtime_checkable it should work.
Step 4: CI setup.
Example for GitHub Actions:
Create a file .github/workflows/type-check.yml:
yaml
name: Type Check
on: [push, pull_request]
jobs:
type-check:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Set up Python
uses: actions/setup-python@v4
with:
python-version: '3.9'
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install mypy typeguard # or pyright, but note that pyright might be installed via npm? Actually, pyright can be installed via pip too (as `pyright`).
- name: Run mypy
run: mypy --strict .
- name: Run tests with typeguard (if you have tests)
# If you have tests, you might want to run them with typeguard. Alternatively, you can use a tool that runs both.
# But note: typeguard is a runtime checker, so it will run when the code is executed. You can run your test suite and if there's a type error, it will raise an exception.
run: |
# Example if you use pytest and have typeguard installed, it will automatically check if you use the @typechecked decorator.
# But if you want to check all functions, you might need to use a different approach (like a custom plugin).
# Alternatively, you can run a script that imports your modules and calls functions with typeguard.
# However, note that typeguard is typically used as a decorator, so it will only check the decorated functions.
pytest
Alternatively, if you don't want to run the entire test suite with typeguard (because it might be slow) and only want to check the types, you might consider:
Using mypy for static checking (which is fast and catches most issues).
Using typeguard only for critical functions and then running a subset of tests that exercise those functions.
But note: the above CI runs mypy and then runs the tests (with typeguard active if you decorated functions). If a type error occurs in a decorated function during the test, the test will fail.
However, if you want to enforce runtime type checks for all functions (without manually decorating), you can use typeguard's install_import_hook to automatically check all functions in a module. But that might be heavy and is not recommended for production.
Alternatively, consider using pydantic for data validation (which also does runtime type checking) for critical data structures (like API request/response models).
Another note: typeguard and mypy might have different interpretations of some types. So it's good to run both.
Also, note that pyright can be run in CI similarly.
Important: Configure your type checker (mypy/pyright) to ignore errors in third-party libraries that don't have type stubs or have incomplete stubs. You can do this in the configuration file.
Additional tools: Consider using pydantic for data validation (which also enforces types at runtime) for critical data (like configuration, API data). This gives you both validation and type safety.
Example with pydantic:
python
from pydantic import BaseModel
class MyModel(BaseModel):
name: str
age: int
# This will raise a validation error at runtime if the data doesn't match.
data = {"name": "John", "age": "thirty"} # This will fail because age is not an int.
model = MyModel(**data)
Pre-commit hooks: Use pre-commit to run mypy (or pyright) on changed files.
Example .pre-commit-config.yaml:
yaml
repos:
- repo: https://github.com/pre-commit/mirrors-mypy
rev: v1.0.0 # Use the version you want
hooks:
- id: mypy
additional_dependencies: [typeguard] # if you use typeguard and want to check code that uses it?
# Note: mypy doesn't run the code, so it doesn't need typeguard. But if you use typeguard's import hook? No, mypy doesn't use that.
# So just mypy is enough for static checking.
Alternatively, for pyright:
yaml
- repo: https://github.com/pre-commit/pyright
rev: v1.1.300 # Use the version you want
hooks:
- id: pyright
Conclusion: By combining static type checking (mypy/pyright), protocols for clear interfaces, runtime checks (typeguard/pydantic) for critical paths, and CI gates, you can achieve a high level of type safety in Python.
However, note that Python is a dynamic language and these tools have limitations. They can't catch every type error, but they catch many.
Let me know if you have any specific questions about any of these steps.
Excellent question! Here's a comprehensive guide to pushing type safety in Python using multiple layers:
Set "python.analysis.typeCheckingMode": "strict" in settings
2. Protocols (Structural Typing)
Define interfaces without inheritance
python
from typing import Protocol, runtime_checkable
from dataclasses import dataclass
@runtime_checkable # Enables isinstance() checks at runtime
class Renderer(Protocol):
def render(self, data: dict) -> str: ...
def validate(self, config: dict) -> bool: ...
@runtime_checkable
class DataSource(Protocol):
def fetch(self, query: str) -> list[dict]: ...
# Implementation doesn't need to explicitly inherit
class JsonRenderer:
def render(self, data: dict) -> str:
return json.dumps(data)
def validate(self, config: dict) -> bool:
return "format" in config
# Type checker knows this works
def process(renderer: Renderer, source: DataSource):
data = source.fetch("SELECT *")
if renderer.validate({"format": "json"}):
return renderer.render(data[0])
Using with generics
python
from typing import TypeVar, Generic, Protocol
T = TypeVar('T')
class Container(Protocol[T]):
def get(self) -> T: ...
def set(self, value: T) -> None: ...
class IntContainer:
def __init__(self) -> None:
self._value: int = 0
def get(self) -> int:
return self._value
def set(self, value: int) -> None:
self._value = value
3. Runtime Checks (Defense in Depth)
typeguard (Automatic runtime checking)
python
from typeguard import typechecked
@typechecked
def process_data(data: list[int], threshold: float) -> bool:
return sum(data) > threshold
# Raises TypeError if called with wrong types
process_data([1, 2, 3], 5.5) # OK
process_data([1, "2", 3], 5.5) # TypeError at call site
Caution: Adds overhead. Use strategically in:
Public API boundaries
Data validation points
Configuration loading
pydantic (Validation + parsing)
python
from pydantic import BaseModel, validator
from typing import List
class User(BaseModel):
id: int
name: str
email: str
tags: List[str] = []
@validator('email')
def email_must_contain_at(cls, v: str) -> str:
if '@' not in v:
raise ValueError('must contain @')
return v
# Automatic validation/conversion
user = User(id=1, name="John", email="john@example.com")
user = User(id="1", name="John", email="john@example.com") # id converted to int
user = User(id=1, name="John") # Missing email -> ValidationError
Manual runtime checks (for critical paths)
python
from typing import cast, get_type_hints
def enforce_types(obj: object, type_hints: dict[str, type]) -> None:
"""Simple runtime type checker for critical functions"""
for attr, expected_type in type_hints.items():
if hasattr(obj, attr):
value = getattr(obj, attr)
if not isinstance(value, expected_type):
raise TypeError(f"{attr} must be {expected_type}, got {type(value)}")
class Config:
timeout: int = 30
retries: int = 3
# In critical initialization
config = Config()
enforce_types(config, get_type_hints(Config))
4. CI/CD Integration (Enforcement)
GitHub Actions Example
yaml
name: Type Check
on: [push, pull_request]
jobs:
type-check:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v4
with:
python-version: '3.11'
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install mypy pyright pydantic typeguard
pip install -e .[dev] # your package with dev dependencies
- name: Run mypy
run: mypy --config-file=mypy.ini src/
- name: Run pyright
run: pyright src/
- name: Run tests with typeguard
run: |
# If using pytest with typeguard
pytest --typeguard-packages=src/
Start with --disallow-untyped-defs and gradually enable stricter checks
Use # type: ignore sparingly and always with comments explaining why
Prefer explicit -> None over implicit None returns
Use cast() sparingly - it bypasses type checking
Write type stubs (.pyi files) for complex C extensions or when you can't modify source
Use reveal_type() during development to see inferred types
Test type hints with mypy's --warn-unreachable to detect dead code
Document protocols - they serve as documentation for expected interfaces
8. Common Pitfalls & Solutions
Problem
Solution
Third-party libs without stubs
pip install types-requests or ignore_missing_imports = true
Dynamic attributes (setattr)
Use cast() or TypedDict with total=False
Duck typing with protocols
Use @runtime_checkable + isinstance() for runtime
Circular imports with types
Move types to separate types.py module
Any propagation
Enable disallow_any_expr = true in mypy
Quick Start Checklist
Add mypy or pyright to dev dependencies
Configure strict mode in CI
Add pre-commit hook for type checking
Define protocols for key interfaces
Add @typechecked or pydantic to API boundaries
Set up CI gate that fails on type errors
Enable warn_unused_ignores to clean up # type: ignore
Use reveal_type() to debug complex type inferences
The key is layered defense: static checking catches most issues early, protocols document interfaces, runtime checks guard critical boundaries, and CI gates prevent regressions. Start conservatively and gradually increase strictness as your codebase adapts.