Claude Code for typeguard: Runtime Type Checking in Python — Claude Skills 360 Blog
Blog / AI / Claude Code for typeguard: Runtime Type Checking in Python
AI

Claude Code for typeguard: Runtime Type Checking in Python

Published: January 8, 2028
Read time: 5 min read
By: Claude Skills 360

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.

Keep Reading

AI

Claude Code for email.contentmanager: Python Email Content Accessors

Read and write EmailMessage body content with Python's email.contentmanager module and Claude Code — email contentmanager ContentManager for the class that maps content types to get and set handler functions allowing EmailMessage to support get_content and set_content with type-specific behaviour, email contentmanager raw_data_manager for the ContentManager instance that handles raw bytes and str payloads without any conversion, email contentmanager content_manager for the standard ContentManager instance used by email.policy.default that intelligently handles text plain text html multipart and binary content types, email contentmanager get_content_text for the handler that returns the decoded text payload of a text-star message part as a str, email contentmanager get_content_binary for the handler that returns the raw decoded bytes payload of a non-text message part, email contentmanager get_data_manager for the get-handler lookup used by EmailMessage get_content to find the right reader function for the content type, email contentmanager set_content text for the handler that creates and sets a text part correctly choosing charset and transfer encoding, email contentmanager set_content bytes for the handler that creates and sets a binary part with base64 encoding and optional filename Content-Disposition, email contentmanager EmailMessage get_content for the method that reads the message body using the registered content manager handlers, email contentmanager EmailMessage set_content for the method that sets the message body and MIME headers in one call, email contentmanager EmailMessage make_alternative make_mixed make_related for the methods that convert a simple message into a multipart container, email contentmanager EmailMessage add_attachment for the method that attaches a file or bytes to a multipart message, and email contentmanager integration with email.message and email.policy and email.mime and io for building high-level email readers attachment extractors text body accessors HTML readers and policy-aware MIME construction pipelines.

5 min read Feb 12, 2029
AI

Claude Code for email.charset: Python Email Charset Encoding

Control header and body encoding for international email with Python's email.charset module and Claude Code — email charset Charset for the class that wraps a character set name with the encoding rules for header encoding and body encoding describing how to encode text for that charset in email messages, email charset Charset header_encoding for the attribute specifying whether headers using this charset should use QP quoted-printable encoding BASE64 encoding or no encoding, email charset Charset body_encoding for the attribute specifying the Content-Transfer-Encoding to use for message bodies in this charset such as QP or BASE64, email charset Charset output_codec for the attribute giving the Python codec name used to encode the string to bytes for the wire format, email charset Charset input_codec for the attribute giving the Python codec name used to decode incoming bytes to str, email charset Charset get_output_charset for returning the output charset name, email charset Charset header_encode for encoding a header string using the charset's header_encoding method, email charset Charset body_encode for encoding body content using the charset's body_encoding, email charset Charset convert for converting a string from the input_codec to the output_codec, email charset add_charset for registering a new charset with custom encoding rules in the global charset registry, email charset add_alias for adding an alias name that maps to an existing registered charset, email charset add_codec for registering a codec name mapping for use by the charset machinery, and email charset integration with email.message and email.mime and email.policy and email.encoders for building international email senders non-ASCII header encoders Content-Transfer-Encoding selectors charset-aware message constructors and MIME encoding pipelines.

5 min read Feb 11, 2029
AI

Claude Code for email.utils: Python Email Address and Header Utilities

Parse and format RFC 2822 email addresses and dates with Python's email.utils module and Claude Code — email utils parseaddr for splitting a display-name plus angle-bracket address string into a realname and email address tuple, email utils formataddr for combining a realname and address string into a properly quoted RFC 2822 address with angle brackets, email utils getaddresses for parsing a list of raw address header strings each potentially containing multiple comma-separated addresses into a list of realname address tuples, email utils parsedate for parsing an RFC 2822 date string into a nine-tuple compatible with time.mktime, email utils parsedate_tz for parsing an RFC 2822 date string into a ten-tuple that includes the UTC offset timezone in seconds, email utils parsedate_to_datetime for parsing an RFC 2822 date string into an aware datetime object with timezone, email utils formatdate for formatting a POSIX timestamp or the current time as an RFC 2822 date string with optional usegmt and localtime flags, email utils format_datetime for formatting a datetime object as an RFC 2822 date string, email utils make_msgid for generating a globally unique Message-ID string with optional idstring and domain components, email utils decode_rfc2231 for decoding an RFC 2231 encoded parameter value into a tuple of charset language and value, email utils encode_rfc2231 for encoding a string as an RFC 2231 encoded parameter value, email utils collapse_rfc2231_value for collapsing a decoded RFC 2231 tuple to a Unicode string, and email utils integration with email.message and email.headerregistry and datetime and time for building address parsers date formatters message-id generators header extractors and RFC-compliant email construction utilities.

5 min read Feb 10, 2029

Put these ideas into practice

Claude Skills 360 gives you production-ready skills for everything in this article — and 2,350+ more. Start free or go all-in.

Back to Blog

Get 360 skills free