typeguard enforces Python type hints at runtime. pip install typeguard. Decorator: from typeguard import typechecked. @typechecked def greet(name: str) -> str: return f"Hello, {name}". greet(123) raises TypeCheckError. Check inline: from typeguard import check_type. check_type(42, str) raises TypeCheckError. check_type(42, int) passes silently. check_type([1,2,3], list[int]) — validates element types too. Return value: @typechecked checks the return annotation — def f() -> int: return "oops" raises. Optional: check_type(None, Optional[str]) — passes. check_type("hi", Optional[str]) — passes. Union: check_type(1, str | int) — passes. Dataclass: @typechecked @dataclass class User: name: str; age: int — validates on __init__. Collection strategy: from typeguard import CollectionCheckStrategy. check_type([1,"x",3], list[int], collection_check_strategy=CollectionCheckStrategy.ALL_ITEMS) — checks every element. Default (FIRST_AND_LAST) checks first and last only — faster for large lists. TypeCheckError: from typeguard import TypeCheckError. try: check_type(val, T) except TypeCheckError as e: print(e). Error includes path: "value is not an instance of str", "item 2 of value is not an instance of int". Suppress: from typeguard import suppress_type_checks. with suppress_type_checks(): call_hot_path(data) — skips checks inside. Import hook: from typeguard import install_import_hook. with install_import_hook("myapp"): import myapp — instruments entire module. pytest: pip install typeguard; add --typeguard-packages=mypackage to pytest args or typeguard_packages in pyproject.toml. pyproject.toml [tool.pytest.ini_options] typeguard_packages = "app". Instrument module: install_import_hook("app.services"). forwardref: typeguard resolves "ClassName" string annotations. Literal: check_type("admin", Literal["user","admin"]) — validates exact values. TypedDict: check_type({"name":"Alice","age":30}, UserDict) — validates key-value pairs. Claude Code generates typeguard decorators, check_type assertions, and pytest integration configs.
CLAUDE.md for typeguard
## typeguard Stack
- Version: typeguard >= 4.2 | pip install typeguard
- Decorator: @typechecked on functions/methods — checks args + return type at call
- Inline: check_type(value, ExpectedType) — raises TypeCheckError on mismatch
- Collections: check_type(lst, list[int], collection_check_strategy=ALL_ITEMS)
- Strategy: CollectionCheckStrategy.ALL_ITEMS | FIRST_AND_LAST (default, faster)
- Suppress: with suppress_type_checks(): ... — skip in hot paths
- pytest: typeguard_packages = "myapp" in pyproject.toml — whole-module checking
typeguard Runtime Type-Checking Pipeline
# app/typed_services.py — typeguard usage patterns
from __future__ import annotations
from dataclasses import dataclass
from decimal import Decimal
from enum import Enum
from typing import Annotated, Literal, Optional, TypedDict, Union
from uuid import UUID
from typeguard import CollectionCheckStrategy, TypeCheckError, check_type, typechecked
# ─────────────────────────────────────────────────────────────────────────────
# Domain types
# ─────────────────────────────────────────────────────────────────────────────
class UserRole(str, Enum):
USER = "user"
MODERATOR = "moderator"
ADMIN = "admin"
@dataclass
class Address:
street: str
city: str
state: str
postal_code: str
country: str = "US"
@dataclass
class User:
id: UUID
email: str
first_name: str
last_name: str
role: UserRole = UserRole.USER
is_active: bool = True
@dataclass
class OrderLine:
product_id: UUID
sku: str
quantity: int
unit_price: Decimal
# TypedDict — check_type validates key presence and value types
class UserPayloadDict(TypedDict):
email: str
first_name: str
last_name: str
role: str
# ─────────────────────────────────────────────────────────────────────────────
# 1. @typechecked decorator — checks args and return type at every call
# ─────────────────────────────────────────────────────────────────────────────
@typechecked
def create_user(
email: str,
first_name: str,
last_name: str,
role: Literal["user", "moderator", "admin"] = "user",
) -> User:
"""
@typechecked validates:
- all argument types against their annotations
- the return value against the return annotation
Raises TypeCheckError (subclass of TypeError) if any check fails.
"""
from uuid import uuid4
return User(
id=uuid4(),
email=email.lower(),
first_name=first_name,
last_name=last_name,
role=UserRole(role),
)
@typechecked
def update_user_role(user: User, new_role: UserRole) -> User:
"""typechecked works with Enum types — validates isinstance(new_role, UserRole)."""
user.role = new_role
return user
@typechecked
def calculate_order_total(lines: list[OrderLine]) -> Decimal:
"""
typechecked checks that lines is a list — but does NOT check element types
by default. Use check_type with ALL_ITEMS for deep list checking.
"""
return sum(line.unit_price * line.quantity for line in lines)
# ─────────────────────────────────────────────────────────────────────────────
# 2. check_type — inline assertions with full generic support
# ─────────────────────────────────────────────────────────────────────────────
def validate_user_payload(raw: dict) -> UserPayloadDict:
"""
Use check_type to validate a raw dict against a TypedDict before processing.
This is useful at service boundaries — e.g., after json.loads().
"""
check_type(raw, UserPayloadDict)
return raw # type: ignore[return-value]
def validate_prices(prices: list) -> list[Decimal]:
"""Validate that every element of a list is a Decimal."""
check_type(
prices,
list[Decimal],
collection_check_strategy=CollectionCheckStrategy.ALL_ITEMS,
)
return prices # type: ignore[return-value]
def validate_event(event: dict) -> None:
"""Validate a JSON-decoded event dict's specific fields."""
check_type(event.get("type"), Literal["user_created", "order_placed", "payment_received"])
check_type(event.get("event_id"), str)
check_type(event.get("occurred_at"), str)
# ─────────────────────────────────────────────────────────────────────────────
# 3. Optional, Union, and nested generic checks
# ─────────────────────────────────────────────────────────────────────────────
def check_optional_address(value: object) -> Optional[Address]:
"""Demonstrates that check_type handles Optional correctly."""
check_type(value, Optional[Address])
return value # type: ignore[return-value]
def check_union_id(value: object) -> str | UUID:
"""Passes if value is str or UUID — fails for int, None, etc."""
check_type(value, str | UUID)
return value # type: ignore[return-value]
def check_nested_dict(value: object) -> dict[str, list[int]]:
"""Deep generic check — validates all keys are str, all values are list[int]."""
check_type(
value,
dict[str, list[int]],
collection_check_strategy=CollectionCheckStrategy.ALL_ITEMS,
)
return value # type: ignore[return-value]
# ─────────────────────────────────────────────────────────────────────────────
# 4. Structured error handling — TypeCheckError
# ─────────────────────────────────────────────────────────────────────────────
def safe_check_type(value: object, expected_type: type) -> list[str]:
"""
Returns [] if value matches expected_type, or a list with the error message.
TypeCheckError.args[0] is a human-readable description of the failure.
"""
try:
check_type(value, expected_type)
return []
except TypeCheckError as exc:
return [str(exc)]
def validate_api_response(response: dict, expected_keys: dict[str, type]) -> list[str]:
"""
Validate that an API response dict has the expected keys with correct types.
Returns all type mismatches.
"""
errors: list[str] = []
for key, expected in expected_keys.items():
if key not in response:
errors.append(f"Missing key: {key!r}")
continue
try:
check_type(response[key], expected)
except TypeCheckError as exc:
errors.append(f"{key!r}: {exc}")
return errors
# ─────────────────────────────────────────────────────────────────────────────
# 5. suppress_type_checks — hot path bypass
# ─────────────────────────────────────────────────────────────────────────────
from typeguard import suppress_type_checks
def process_bulk_events(events: list[dict]) -> list[str]:
"""
Validation is done once at the boundary; suppress inside the loop
to avoid per-event overhead in high-throughput paths.
"""
# Validate the outer container once
check_type(events, list[dict])
results = []
with suppress_type_checks():
for event in events:
# @typechecked functions inside here skip their checks
results.append(event.get("event_id", ""))
return results
# ─────────────────────────────────────────────────────────────────────────────
# Demo
# ─────────────────────────────────────────────────────────────────────────────
if __name__ == "__main__":
from uuid import uuid4
# @typechecked — valid call
user = create_user("[email protected]", "Alice", "Smith", role="admin")
print(f"Created: {user.first_name} {user.last_name} role={user.role.value}")
# @typechecked — wrong arg type
try:
create_user(123, "Alice", "Smith") # type: ignore[arg-type]
except TypeCheckError as e:
print(f"TypeCheckError: {e}")
# check_type — Literal validation
try:
check_type("superuser", Literal["user", "moderator", "admin"])
except TypeCheckError as e:
print(f"Literal error: {e}")
# check_type — Optional
check_type(None, Optional[str]) # passes
check_type("hi", Optional[str]) # passes
print("Optional checks passed")
# check_type — deep list[Decimal]
from decimal import Decimal
prices = [Decimal("9.99"), Decimal("19.99"), Decimal("39.99")]
validated = validate_prices(prices)
print(f"Prices valid: {validated}")
try:
validate_prices([9.99, 19.99, "bad"]) # float + str fail
except TypeCheckError as e:
print(f"Price list error: {e}")
# TypedDict validation
payload = {"email": "[email protected]", "first_name": "A", "last_name": "B", "role": "user"}
validated_payload = validate_user_payload(payload)
print(f"Payload valid: {validated_payload['email']}")
# API response validation
response = {"id": 123, "email": "[email protected]", "role": "admin", "count": "not-int"}
errors = validate_api_response(response, {"id": int, "email": str, "count": int})
print(f"Response errors: {errors}")
For the mypy alternative — mypy catches type errors at analysis time without running the code, while typeguard catches type errors at runtime when values from external sources (JSON parsing, database rows, user input) flow into typed code — the two tools are complementary: mypy removes logical type bugs during development, typeguard catches data boundary violations in production. For the pydantic alternative — Pydantic focuses on data parsing and serialization — the primary use case is converting unstructured input (dicts, JSON) into validated model instances — while @typechecked enforces contracts on existing Python functions without changing any class definitions, making it the right tool for adding runtime safety to a service layer that already uses dataclasses or attrs without rebuilding the models. The Claude Skills 360 bundle includes typeguard skill sets covering @typechecked for function-level enforcement, check_type for inline assertions, CollectionCheckStrategy ALL_ITEMS vs FIRST_AND_LAST, TypeCheckError handling and message extraction, Optional/Union/Literal/TypedDict/Generic checking, suppress_type_checks for hot paths, install_import_hook for whole-module instrumentation, pytest —typeguard-packages integration, and combining typeguard with mypy for layered type safety. Start with the free tier to try runtime type-checking code generation.