Claude Code for typing: Python Type Annotations and Static Typing — Claude Skills 360 Blog
Blog / AI / Claude Code for typing: Python Type Annotations and Static Typing
AI

Claude Code for typing: Python Type Annotations and Static Typing

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

Python’s typing module provides type annotation building blocks for static analysis with mypy/pyright. from typing import Any, Callable, ClassVar, Final, Generic, Literal, NamedTuple, Optional, Protocol, TypeVar, Union, overload, cast, TYPE_CHECKING. TypeVar: T = TypeVar("T"); K = TypeVar("K", bound=Hashable). Generic: class Stack(Generic[T]): def push(self, item: T) -> None. Protocol: class Sized(Protocol): def __len__(self) -> int — structural subtyping. TypedDict: class Config(TypedDict): host: str; port: int. Literal: def set_level(level: Literal["DEBUG","INFO","WARNING"]) -> None. Union: str | int (Python 3.10+) or Union[str, int]. Optional: Optional[str] == str | None. overload: @overload def fn(x: int) -> int: ...; @overload def fn(x: str) -> str: .... cast: x = cast(int, some_value) — type-checker hint only, no runtime effect. TYPE_CHECKING: if TYPE_CHECKING: from heavy_module import HeavyType. Final: MAX: Final = 100 — immutable. ClassVar: class C: count: ClassVar[int] = 0 — not in instances. Annotated: Height = Annotated[float, Gt(0)]. ParamSpec: P = ParamSpec("P") — preserve callable signature in decorators. TypeGuard: def is_str(val: object) -> TypeGuard[str]: return isinstance(val, str). Self: def copy(self) -> Self (Python 3.11+). get_type_hints: typing.get_type_hints(cls) — resolved annotations dict. Claude Code generates generic containers, Protocol interfaces, decorator signatures, and TypedDict schemas.

CLAUDE.md for typing

## typing Stack
- Stdlib: from typing import TypeVar, Generic, Protocol, TypedDict, Literal, overload, TYPE_CHECKING
- TypeVar: T = TypeVar("T") | K = TypeVar("K", bound=Hashable) | use in Generic[T] and -> T
- Protocol: structural interface — no inheritance needed; use @runtime_checkable for isinstance
- Overload: @overload stubs + un-decorated impl — one per distinct signature
- Self: -> Self for fluent interfaces (Python 3.11+; use TypeVar T for 3.10)
- TYPE_CHECKING: guard heavy imports used only for annotations

typing Annotation Pipeline

# app/typed.py — TypeVar, Generic, Protocol, TypedDict, Literal, overload, ParamSpec
from __future__ import annotations

import copy
import functools
import sys
from typing import (
    TYPE_CHECKING,
    Annotated,
    Any,
    Callable,
    ClassVar,
    Final,
    Generic,
    Hashable,
    Iterator,
    Literal,
    NamedTuple,
    Optional,
    Protocol,
    Sequence,
    TypeVar,
    Union,
    cast,
    get_type_hints,
    overload,
    runtime_checkable,
)

if sys.version_info >= (3, 10):
    from typing import ParamSpec, TypeGuard
else:
    from typing import TypeVar as ParamSpec  # fallback (no-op typing)
    TypeGuard = Any  # type: ignore

if TYPE_CHECKING:
    pass  # place heavy, annotation-only imports here

# ─────────────────────────────────────────────────────────────────────────────
# 1. TypeVar + Generic containers
# ─────────────────────────────────────────────────────────────────────────────

T  = TypeVar("T")
K  = TypeVar("K", bound=Hashable)
V  = TypeVar("V")
T_co = TypeVar("T_co", covariant=True)


class Stack(Generic[T]):
    """
    Generic LIFO stack.

    Example:
        s: Stack[int] = Stack()
        s.push(1)
        s.push(2)
        top = s.pop()   # 2
    """

    def __init__(self) -> None:
        self._items: list[T] = []

    def push(self, item: T) -> None:
        self._items.append(item)

    def pop(self) -> T:
        return self._items.pop()

    def peek(self) -> T:
        return self._items[-1]

    def __len__(self) -> int:
        return len(self._items)

    def __bool__(self) -> bool:
        return bool(self._items)

    def __iter__(self) -> Iterator[T]:
        return reversed(self._items)


class Result(Generic[T]):
    """
    Typed result that holds either a success value or an error.

    Example:
        ok:  Result[int] = Result.ok(42)
        err: Result[int] = Result.err("not found")
        if ok.is_ok:
            print(ok.value)
    """

    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

    @property
    def value(self) -> T:
        if self._error is not None:
            raise ValueError(self._error)
        return cast(T, self._value)

    @property
    def error(self) -> str | None:
        return self._error

    def map(self, fn: Callable[[T], V]) -> Result[V]:
        if self._error:
            return Result.err(self._error)  # type: ignore[return-value]
        return Result.ok(fn(cast(T, self._value)))

    def __repr__(self) -> str:
        if self.is_ok:
            return f"Ok({self._value!r})"
        return f"Err({self._error!r})"


# ─────────────────────────────────────────────────────────────────────────────
# 2. Protocol — structural subtyping
# ─────────────────────────────────────────────────────────────────────────────

@runtime_checkable
class Serializable(Protocol):
    """
    Any object that can serialize itself to a dict.

    Example:
        def save(obj: Serializable) -> None:
            json.dump(obj.to_dict(), f)
    """
    def to_dict(self) -> dict[str, Any]: ...


@runtime_checkable
class Comparable(Protocol[T_co]):
    """Structural protocol for objects supporting < and ==."""
    def __lt__(self, other: Any) -> bool: ...
    def __eq__(self, other: object) -> bool: ...


@runtime_checkable
class Closeable(Protocol):
    """Structural protocol for objects with a .close() method."""
    def close(self) -> None: ...


def process_serializable(obj: Serializable) -> str:
    """
    Accept any object matching the Serializable protocol.

    Example:
        class User:
            def to_dict(self): return {"id": self.id, "name": self.name}

        process_serializable(User(id=1, name="Alice"))  # works — no inheritance needed
    """
    import json
    return json.dumps(obj.to_dict())


# ─────────────────────────────────────────────────────────────────────────────
# 3. TypedDict schemas
# ─────────────────────────────────────────────────────────────────────────────

from typing import TypedDict  # noqa: E402


class UserConfig(TypedDict):
    """Typed dict for user configuration."""
    host:       str
    port:       int
    debug:      bool


class UserConfigOptional(TypedDict, total=False):
    """TypedDict with all-optional keys."""
    timeout:    float
    max_retry:  int
    log_level:  str


class DatabaseConfig(TypedDict):
    """Nested TypedDict."""
    url:      str
    pool_size: int
    options:  UserConfigOptional


class APIResponse(TypedDict):
    """Typed API response envelope."""
    success: bool
    data:    Any
    error:   Optional[str]
    meta:    dict[str, Any]


# ─────────────────────────────────────────────────────────────────────────────
# 4. Literal types
# ─────────────────────────────────────────────────────────────────────────────

LogLevel  = Literal["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"]
HTTPVerb  = Literal["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"]
SortOrder = Literal["asc", "desc"]
OutputFmt = Literal["json", "csv", "parquet", "arrow"]


def set_log_level(level: LogLevel) -> None:
    """
    Only accepts valid log level strings — caught at type-check time.

    Example:
        set_log_level("INFO")    # OK
        set_log_level("TRACE")   # mypy/pyright error
    """
    import logging
    logging.getLogger().setLevel(level)


def make_request(
    verb: HTTPVerb,
    url: str,
    *,
    order: SortOrder = "asc",
    fmt: OutputFmt = "json",
) -> dict:
    return {"verb": verb, "url": url, "order": order, "fmt": fmt}


# ─────────────────────────────────────────────────────────────────────────────
# 5. overload — multiple return types
# ─────────────────────────────────────────────────────────────────────────────

@overload
def parse(value: str) -> int: ...
@overload
def parse(value: bytes) -> str: ...
@overload
def parse(value: int) -> float: ...


def parse(value: str | bytes | int) -> int | str | float:
    """
    Typed multi-dispatch: return type depends on input type.

    Example:
        x: int   = parse("42")       # str → int
        y: str   = parse(b"hello")   # bytes → str
        z: float = parse(7)          # int → float
    """
    if isinstance(value, str):
        return int(value)
    if isinstance(value, bytes):
        return value.decode()
    return float(value)


# ─────────────────────────────────────────────────────────────────────────────
# 6. TypeGuard + type narrowing
# ─────────────────────────────────────────────────────────────────────────────

def is_str_list(val: list[Any]) -> TypeGuard:  # type: ignore[type-arg]
    """
    Narrow list[Any] to list[str] after this guard returns True.

    Example:
        data: list[Any] = get_raw()
        if is_str_list(data):
            joined: str = ", ".join(data)  # type-safe
    """
    return all(isinstance(item, str) for item in val)


def is_int(val: object) -> bool:
    """isinstance guard usable in type-narrowing branches."""
    return isinstance(val, int)


# ─────────────────────────────────────────────────────────────────────────────
# 7. Decorator with ParamSpec
# ─────────────────────────────────────────────────────────────────────────────

if sys.version_info >= (3, 10):
    from typing import ParamSpec as _PS
    _P = _PS("_P")
else:
    _P = TypeVar("_P")  # type: ignore[assignment]


def logged(fn: Callable) -> Callable:
    """
    Decorator that preserves the wrapped function's full signature.
    With ParamSpec this is fully type-safe on Python 3.10+.

    Example:
        @logged
        def add(x: int, y: int) -> int:
            return x + y

        add(1, 2)   # type checker knows return=int and args=(int, int)
    """
    @functools.wraps(fn)
    def wrapper(*args, **kwargs):
        import logging
        logging.getLogger(fn.__module__).debug("call %s", fn.__name__)
        result = fn(*args, **kwargs)
        logging.getLogger(fn.__module__).debug("done %s", fn.__name__)
        return result
    return wrapper


# ─────────────────────────────────────────────────────────────────────────────
# 8. Final + ClassVar
# ─────────────────────────────────────────────────────────────────────────────

MAX_RETRIES: Final[int] = 3
DEFAULT_TIMEOUT: Final[float] = 30.0
API_VERSION: Final = "v2"


class AppConfig:
    _instances: ClassVar[dict[str, AppConfig]] = {}
    _registry:  ClassVar[list[str]] = []

    def __init__(self, name: str, debug: bool = False) -> None:
        self.name  = name
        self.debug = debug
        AppConfig._registry.append(name)


# ─────────────────────────────────────────────────────────────────────────────
# Demo
# ─────────────────────────────────────────────────────────────────────────────

if __name__ == "__main__":
    import json

    print("=== typing demo ===")

    print("\n--- Generic Stack[int] ---")
    s: Stack[int] = Stack()
    for i in [1, 2, 3]:
        s.push(i)
    print(f"  len={len(s)}  top={s.peek()}  pop={s.pop()}")

    print("\n--- Result[int] ---")
    r = Result.ok(42).map(lambda x: x * 2)
    print(f"  ok.map(*2): {r}")
    r2 = Result.err("not found")
    print(f"  err: {r2}  is_ok={r2.is_ok}  error={r2.error!r}")

    print("\n--- Protocol (Serializable) ---")
    class Point:
        def __init__(self, x, y):
            self.x, self.y = x, y
        def to_dict(self):
            return {"x": self.x, "y": self.y}

    p = Point(3, 4)
    print(f"  isinstance(p, Serializable): {isinstance(p, Serializable)}")
    print(f"  process_serializable: {process_serializable(p)}")

    print("\n--- TypedDict ---")
    cfg: UserConfig = {"host": "localhost", "port": 8080, "debug": True}
    print(f"  cfg: {cfg}")

    print("\n--- Literal ---")
    req = make_request("GET", "https://api.example.com/data", order="desc", fmt="parquet")
    print(f"  req: {req}")

    print("\n--- overload parse ---")
    print(f"  parse('42')         = {parse('42')!r}")
    print(f"  parse(b'hello')     = {parse(b'hello')!r}")
    print(f"  parse(7)            = {parse(7)!r}")

    print("\n--- TypeGuard ---")
    data: list[Any] = ["a", "b", "c"]
    print(f"  is_str_list(['a','b','c']): {is_str_list(data)}")
    print(f"  is_str_list([1,2,3]):       {is_str_list([1,2,3])}")

    print("\n--- Final + ClassVar ---")
    print(f"  MAX_RETRIES={MAX_RETRIES}  API_VERSION={API_VERSION!r}")
    AppConfig("app1")
    AppConfig("app2")
    print(f"  AppConfig._registry: {AppConfig._registry}")

    print("\n--- get_type_hints ---")
    hints = get_type_hints(UserConfig)
    print(f"  UserConfig hints: {hints}")

    print("\n=== done ===")

For the mypy alternative — mypy is the canonical static type checker for Python that reads type annotations and reports type errors before runtime; typing provides just the annotation building blocks — both are used together: write annotations with typing, validate them with mypy --strict; pyright (Microsoft) is a faster alternative checker with better LSP integration that powers Pylance in VS Code. For the beartype alternative — beartype (PyPI) provides runtime type checking by validating actual call arguments against type annotations at O(1) per call, catching type errors that static checkers cannot see (e.g. data from external APIs); typing annotations alone are ignored at runtime by default — use @beartype decorator or BeartypeConf when you need runtime enforcement at API boundaries, typing alone for static analysis with mypy/pyright in CI. The Claude Skills 360 bundle includes typing skill sets covering Stack/Result Generic containers, Serializable/Comparable/Closeable Protocol interfaces, UserConfig/DatabaseConfig/APIResponse TypedDict schemas, LogLevel/HTTPVerb/SortOrder Literal types, overload parse() multi-signature, is_str_list() TypeGuard narrowing, logged() decorator with ParamSpec, and Final/ClassVar class-level constants. Start with the free tier to try gradual static typing and typing annotation pipeline 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