mypy is the standard static type checker for Python. pip install mypy. Run: mypy src/. Strict: mypy --strict src/. Ignore missing stubs: mypy --ignore-missing-imports src/. Config in pyproject.toml: [tool.mypy] python_version="3.12" strict=true ignore_missing_imports=true. Per-module overrides: [[tool.mypy.overrides]] module="legacy.*" ignore_errors=true. Inline ignore: x = untyped_fn() # type: ignore[no-untyped-call]. Reveal type: reveal_type(variable) — mypy prints the inferred type. Daemon: dmypy run -- src/ — incremental, much faster for large codebases. dmypy status, dmypy stop. Stub generation: stubgen -p mypackage -o stubs/. Type aliases: Vector = list[float]. TypeAlias (3.10+): from typing import TypeAlias; Vector: TypeAlias = list[float]. TypeVar: T = TypeVar("T"). Bounded: T = TypeVar("T", bound=Comparable). Constrained: T = TypeVar("T", int, str). Generic class: class Stack(Generic[T]). Protocol: class Sizeable(Protocol): def __len__(self) -> int: .... TypedDict: class UserDict(TypedDict): id: int; name: str. Total=False: class Partial(TypedDict, total=False): nickname: str. Literal: def set_level(level: Literal["DEBUG","INFO","WARNING"]) -> None. Overload: @overload def process(x: int) -> int: ... / @overload def process(x: str) -> str: ... then real impl. Final: MAX: Final = 100. ClassVar: count: ClassVar[int] = 0. cast: from typing import cast; x = cast(int, raw_value). assert_never: from typing import assert_never for exhaustive match. ParamSpec: P = ParamSpec("P") for decorator typing. Concatenate: Callable[Concatenate[int, P], T]. py.typed marker: touch src/mypackage/py.typed — declares package ships inline types. Claude Code generates mypy configurations, typed API signatures, and Protocol interfaces for duck-typed code.
CLAUDE.md for mypy
## mypy Stack
- Version: mypy >= 1.8 | pip install mypy
- Run: mypy src/ | mypy --strict src/
- Config: pyproject.toml [tool.mypy] strict=true ignore_missing_imports=true
- Daemon: dmypy run -- src/ (incremental, fast on large codebases)
- Suppress: # type: ignore[error-code] (specific) never bare # type: ignore
- Debug: reveal_type(expr) — mypy prints inferred type, remove before commit
- Stubs: stubgen -p pkg -o stubs/ | pip install types-requests types-PyYAML
mypy Static Typing Pipeline
# src/typed_pipeline.py — mypy type annotation patterns
# Run: mypy src/typed_pipeline.py --strict
from __future__ import annotations
import functools
import logging
from collections.abc import Callable, Iterator, Sequence
from typing import (
TYPE_CHECKING,
Any,
ClassVar,
Final,
Generic,
Literal,
NamedTuple,
ParamSpec,
Protocol,
TypeAlias,
TypeVar,
TypedDict,
assert_never,
cast,
overload,
runtime_checkable,
)
if TYPE_CHECKING:
from pathlib import Path
logger = logging.getLogger(__name__)
# ─────────────────────────────────────────────────────────────────────────────
# Type aliases
# ─────────────────────────────────────────────────────────────────────────────
JsonValue: TypeAlias = dict[str, Any] | list[Any] | str | int | float | bool | None
Headers: TypeAlias = dict[str, str]
StatusCode: TypeAlias = int
# ─────────────────────────────────────────────────────────────────────────────
# TypedDict — typed dicts for structured data
# ─────────────────────────────────────────────────────────────────────────────
class UserDict(TypedDict):
id: int
name: str
email: str
role: str
class UserUpdateDict(TypedDict, total=False):
"""Partial update — all fields optional."""
name: str
email: str
role: str
class PaginatedResponse(TypedDict):
items: list[UserDict]
total: int
page: int
page_size: int
next_page: int | None
# ─────────────────────────────────────────────────────────────────────────────
# Literal types — constrain to specific values
# ─────────────────────────────────────────────────────────────────────────────
LogLevel: TypeAlias = Literal["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"]
SortOrder: TypeAlias = Literal["asc", "desc"]
HttpMethod: TypeAlias = Literal["GET", "POST", "PUT", "PATCH", "DELETE"]
def set_log_level(level: LogLevel) -> None:
logging.getLogger().setLevel(level)
def sort_users(
users: list[UserDict],
key: Literal["name", "email", "id"] = "name",
order: SortOrder = "asc",
) -> list[UserDict]:
reverse = order == "desc"
return sorted(users, key=lambda u: u[key], reverse=reverse) # type: ignore[literal-required]
# ─────────────────────────────────────────────────────────────────────────────
# Protocol — structural subtyping (duck typing with types)
# ─────────────────────────────────────────────────────────────────────────────
@runtime_checkable
class Closeable(Protocol):
def close(self) -> None: ...
@runtime_checkable
class Repository(Protocol[TypeVar("T")]): # type: ignore[misc]
def get(self, id: int) -> Any: ...
def save(self, entity: Any) -> None: ...
def delete(self, id: int) -> bool: ...
def list(self, page: int, page_size: int) -> list[Any]: ...
class Cacheable(Protocol):
"""Any object that can be serialized to/from a cache."""
def to_cache_key(self) -> str: ...
def to_cache_value(self) -> bytes: ...
@classmethod
def from_cache_value(cls, data: bytes) -> "Cacheable": ...
# ─────────────────────────────────────────────────────────────────────────────
# TypeVar and Generic classes
# ─────────────────────────────────────────────────────────────────────────────
T = TypeVar("T")
K = TypeVar("K")
V = TypeVar("V")
E = TypeVar("E", bound=Exception)
class Result(Generic[T]):
"""
A Result monad — either Ok(value) or Err(error).
Eliminates exception-driven control flow for expected failures.
"""
def __init__(self, value: T | None, error: str | None) -> None:
self._value = value
self._error = error
@classmethod
def ok(cls, value: T) -> "Result[T]":
return cls(value, None)
@classmethod
def err(cls, error: str) -> "Result[T]":
return cls(None, error)
@property
def is_ok(self) -> bool:
return self._error is None
def unwrap(self) -> T:
if self._error is not None:
raise ValueError(f"Result is an error: {self._error}")
assert self._value is not None
return self._value
def unwrap_or(self, default: T) -> T:
return self._value if self._value is not None else default
def map(self, fn: Callable[[T], V]) -> "Result[V]":
if self.is_ok:
return Result.ok(fn(self.unwrap()))
return Result.err(self._error or "unknown error")
class Stack(Generic[T]):
"""Type-safe generic stack."""
def __init__(self) -> None:
self._items: list[T] = []
def push(self, item: T) -> None:
self._items.append(item)
def pop(self) -> T:
if not self._items:
raise IndexError("Stack is empty")
return self._items.pop()
def peek(self) -> T:
if not self._items:
raise IndexError("Stack is empty")
return self._items[-1]
def __len__(self) -> int:
return len(self._items)
def __iter__(self) -> Iterator[T]:
return iter(reversed(self._items))
# ─────────────────────────────────────────────────────────────────────────────
# @overload — multiple call signatures
# ─────────────────────────────────────────────────────────────────────────────
@overload
def parse_id(value: str) -> int: ...
@overload
def parse_id(value: int) -> int: ...
@overload
def parse_id(value: None) -> None: ...
def parse_id(value: str | int | None) -> int | None:
"""Parse an ID from string, int, or None. Type-safe via overloads."""
if value is None:
return None
return int(value)
@overload
def get_config(key: str, default: str) -> str: ...
@overload
def get_config(key: str, default: None = None) -> str | None: ...
def get_config(key: str, default: str | None = None) -> str | None:
import os
return os.environ.get(key, default)
# ─────────────────────────────────────────────────────────────────────────────
# ParamSpec — typed decorators that preserve signatures
# ─────────────────────────────────────────────────────────────────────────────
P = ParamSpec("P")
R = TypeVar("R")
def log_call(fn: Callable[P, R]) -> Callable[P, R]:
"""Decorator that logs function calls — preserves full type signature."""
@functools.wraps(fn)
def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
logger.debug("Calling %s", fn.__name__)
result = fn(*args, **kwargs)
logger.debug("Done %s", fn.__name__)
return result
return wrapper
def retry_on(
exc_type: type[E],
max_attempts: int = 3,
) -> Callable[[Callable[P, R]], Callable[P, R]]:
"""Parameterized retry decorator — type-safe with ParamSpec."""
def decorator(fn: Callable[P, R]) -> Callable[P, R]:
@functools.wraps(fn)
def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
for attempt in range(max_attempts):
try:
return fn(*args, **kwargs)
except exc_type:
if attempt == max_attempts - 1:
raise
raise RuntimeError("unreachable")
return wrapper
return decorator
# ─────────────────────────────────────────────────────────────────────────────
# NamedTuple — typed tuples
# ─────────────────────────────────────────────────────────────────────────────
class Point(NamedTuple):
x: float
y: float
label: str = ""
class BoundingBox(NamedTuple):
x_min: float
y_min: float
x_max: float
y_max: float
@property
def width(self) -> float:
return self.x_max - self.x_min
@property
def height(self) -> float:
return self.y_max - self.y_min
@property
def area(self) -> float:
return self.width * self.height
# ─────────────────────────────────────────────────────────────────────────────
# Final and ClassVar
# ─────────────────────────────────────────────────────────────────────────────
MAX_RETRIES: Final = 5
DEFAULT_TIMEOUT: Final[float] = 30.0
class APIClient:
BASE_URL: ClassVar[str] = "https://api.example.com/v1"
_instance_count: ClassVar[int] = 0
def __init__(self, token: str, timeout: float = DEFAULT_TIMEOUT) -> None:
self.token = token
self.timeout = timeout
APIClient._instance_count += 1
@classmethod
def instance_count(cls) -> int:
return cls._instance_count
# ─────────────────────────────────────────────────────────────────────────────
# assert_never — exhaustive type narrowing
# ─────────────────────────────────────────────────────────────────────────────
Status: TypeAlias = Literal["pending", "active", "cancelled", "expired"]
def handle_status(status: Status) -> str:
if status == "pending":
return "Awaiting activation"
elif status == "active":
return "Currently active"
elif status == "cancelled":
return "Cancelled by user"
elif status == "expired":
return "Subscription expired"
else:
assert_never(status) # mypy verifies all branches are covered
# ─────────────────────────────────────────────────────────────────────────────
# cast — escape hatch for untyped third-party return values
# ─────────────────────────────────────────────────────────────────────────────
def load_user_from_db(row: Any) -> UserDict:
"""
cast() tells mypy "I know the type even though the source is Any."
Use sparingly — only at untyped system boundaries.
"""
return cast(UserDict, {
"id": row["id"],
"name": row["name"],
"email": row["email"],
"role": row.get("role", "user"),
})
# ─────────────────────────────────────────────────────────────────────────────
# pyproject.toml mypy configuration (as string for reference)
# ─────────────────────────────────────────────────────────────────────────────
PYPROJECT_MYPY = """
[tool.mypy]
python_version = "3.12"
strict = true
# Omit for libraries where stubs are unavailable
ignore_missing_imports = true
# Show error codes so # type: ignore[code] can be targeted
show_error_codes = true
# Warn about imports with no stubs (helpful for finding what to install)
warn_return_any = true
warn_unused_ignores = true
warn_unused_configs = true
# Disallow dynamic typing
disallow_any_generics = true
disallow_subclassing_any = true
# Per-module overrides — relax rules for legacy or generated code
[[tool.mypy.overrides]]
module = "legacy.*"
ignore_errors = true
[[tool.mypy.overrides]]
module = "alembic.*"
ignore_missing_imports = true
[[tool.mypy.overrides]]
module = "tests.*"
disallow_untyped_defs = false
"""
# ─────────────────────────────────────────────────────────────────────────────
# .mypy.ini alternative
# ─────────────────────────────────────────────────────────────────────────────
MYPY_INI = """
[mypy]
python_version = 3.12
strict = True
ignore_missing_imports = True
show_error_codes = True
warn_unused_ignores = True
[mypy-legacy.*]
ignore_errors = True
[mypy-tests.*]
disallow_untyped_defs = False
"""
if __name__ == "__main__":
# Demonstrate generic Stack
int_stack: Stack[int] = Stack()
int_stack.push(1)
int_stack.push(2)
print(f"Stack peek: {int_stack.peek()}") # 2
# Result monad
def divide(a: int, b: int) -> Result[float]:
if b == 0:
return Result.err("Division by zero")
return Result.ok(a / b)
r = divide(10, 2).map(lambda x: x * 100)
print(f"Result: {r.unwrap()}") # 500.0
# BoundingBox NamedTuple
box = BoundingBox(0, 0, 100, 50)
print(f"Box area: {box.area}") # 5000.0
# Overloaded parse_id
print(parse_id("42")) # 42
print(parse_id(None)) # None
For the pyright alternative — pyright (used by Pylance in VS Code) applies stricter generic inference and reports more errors than mypy’s default mode, but mypy’s --strict flag enables the same rigour and mypy has deeper ecosystem integration: dmypy run -- incremental daemon mode finishes in under a second on a 100k-line codebase versus a cold run, stubgen generates .pyi stub files for C-extension packages, and [[tool.mypy.overrides]] applies relaxed rules to legacy or generated code (Alembic migrations, protobuf output) without disabling checks project-wide. For the inline annotations everywhere alternative — the most impactful entry point is Protocol: replacing def process(repo: Any) -> None with def process(repo: Repository) -> None catches 80% of type errors with no changes to callers, TypedDict eliminates dict[str, Any] for structured data returned by database queries or JSON APIs, and overload decorators let functions like parse_id(value: str | int | None) return the exact type the caller expects—str input returns int, None input returns None—without runtime branching. The Claude Skills 360 bundle includes mypy skill sets covering strict mode configuration, TypedDict and TypeVar patterns, Protocol structural subtyping, Literal and assert_never exhaustiveness, overload signatures, ParamSpec decorator typing, pyproject.toml per-module overrides, dmypy daemon workflow, cast and reveal_type debugging, and py.typed marker for library authors. Start with the free tier to try static type checking code generation.