Claude Code for mypy: Static Type Checking in Python — Claude Skills 360 Blog
Blog / AI / Claude Code for mypy: Static Type Checking in Python
AI

Claude Code for mypy: Static Type Checking in Python

Published: December 16, 2027
Read time: 5 min read
By: Claude Skills 360

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.

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