Claude Code for dataclasses: Structured Data Classes in Python — Claude Skills 360 Blog
Blog / AI / Claude Code for dataclasses: Structured Data Classes in Python
AI

Claude Code for dataclasses: Structured Data Classes in Python

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

Python dataclasses auto-generate __init__, __repr__, __eq__ from field annotations. from dataclasses import dataclass, field. Basic: @dataclass class Point: x: float; y: float. Default: @dataclass class Config: debug: bool = False; port: int = 8080. Mutable default: tags: list = field(default_factory=list). Computed: name: str = field(init=False). post_init: def __post_init__(self): if self.x < 0: raise ValueError(...). asdict: from dataclasses import asdict; asdict(point) → dict. astuple: astuple(point) → tuple. replace: from dataclasses import replace; p2 = replace(p, y=10). frozen: @dataclass(frozen=True) — immutable, hashable. order: @dataclass(order=True) — adds <,>,<=,>=. slots: @dataclass(slots=True) (Python 3.10+) — faster attribute access, less memory. kw_only: @dataclass(kw_only=True) (Python 3.10+). KW_ONLY sentinel: field1: int; _: KW_ONLY; field2: str. InitVar: invite_code: InitVar[str] — passed to init but not stored. ClassVar: count: ClassVar[int] = 0 — not in init. fields(): from dataclasses import fields; [(f.name, f.type) for f in fields(cls)]. is_dataclass(): from dataclasses import is_dataclass; is_dataclass(obj). make_dataclass: D = make_dataclass("D", [("x",int),("y",int)]). Inheritance: @dataclass class Child(Parent): extra: str. JSON: json.dumps(asdict(obj)). Claude Code generates typed data models, DTO classes, config dataclasses, and serialization helpers.

CLAUDE.md for dataclasses

## dataclasses Stack
- Stdlib: from dataclasses import dataclass, field, asdict, astuple, replace, fields
- Basic: @dataclass | @dataclass(frozen=True) | @dataclass(order=True, slots=True)
- Field: field(default=val) | field(default_factory=list) | field(repr=False, compare=False)
- Validate: def __post_init__(self): validate fields, raise ValueError
- Serialize: asdict(obj) → dict | json.dumps(asdict(obj)) | replace(obj, field=newval)
- Introspect: fields(cls) | is_dataclass(obj) | f.name, f.type, f.default for f in fields(cls)

dataclasses Modeling Pipeline

# app/models.py — dataclasses with validation, serialization, inheritance, factories
from __future__ import annotations

import json
import re
from dataclasses import (
    KW_ONLY,
    ClassVar,
    InitVar,
    asdict,
    astuple,
    dataclass,
    field,
    fields,
    is_dataclass,
    make_dataclass,
    replace,
)
from datetime import date, datetime
from typing import Any


# ─────────────────────────────────────────────────────────────────────────────
# 1. Basic data models
# ─────────────────────────────────────────────────────────────────────────────

@dataclass
class Point:
    """
    Simple 2D point.

    Example:
        p = Point(1.0, 2.0)
        p2 = replace(p, y=5.0)
        assert p2.x == 1.0 and p2.y == 5.0
    """
    x: float
    y: float

    def distance_to(self, other: Point) -> float:
        return ((self.x - other.x) ** 2 + (self.y - other.y) ** 2) ** 0.5


@dataclass(frozen=True, order=True)
class Version:
    """
    Immutable, comparable semantic version.

    Example:
        v1 = Version(2, 1, 0)
        v2 = Version(2, 0, 3)
        assert v1 > v2
        versions = sorted([v2, v1, Version(1, 0, 0)])
    """
    major: int
    minor: int
    patch: int = 0

    def __str__(self) -> str:
        return f"{self.major}.{self.minor}.{self.patch}"

    @classmethod
    def parse(cls, s: str) -> Version:
        parts = [int(p) for p in s.split(".", 2)]
        return cls(*parts) if len(parts) >= 2 else cls(parts[0], 0, 0)


@dataclass(slots=True)
class Vector2D:
    """
    Memory-efficient 2D vector (slots=True saves ~30% memory vs dict-backed).

    Example:
        v = Vector2D(3.0, 4.0)
        print(v.length())   # 5.0
    """
    x: float
    y: float

    def length(self) -> float:
        return (self.x ** 2 + self.y ** 2) ** 0.5

    def add(self, other: Vector2D) -> Vector2D:
        return Vector2D(self.x + other.x, self.y + other.y)

    def scale(self, factor: float) -> Vector2D:
        return Vector2D(self.x * factor, self.y * factor)


# ─────────────────────────────────────────────────────────────────────────────
# 2. Validated models with __post_init__
# ─────────────────────────────────────────────────────────────────────────────

@dataclass
class EmailAddress:
    """
    Validated email with normalized representation.

    Example:
        email = EmailAddress("  [email protected]  ")
        print(email.address)   # "[email protected]"
        print(email.domain)    # "example.com"
    """
    _raw: InitVar[str]
    address: str = field(init=False)
    local:   str = field(init=False, repr=False)
    domain:  str = field(init=False)
    _pattern: ClassVar[re.Pattern] = re.compile(
        r"^[a-zA-Z0-9._%+\-]+@[a-zA-Z0-9.\-]+\.[a-zA-Z]{2,}$"
    )

    def __post_init__(self, _raw: str) -> None:
        normalized = _raw.strip().lower()
        if not self._pattern.match(normalized):
            raise ValueError(f"Invalid email address: {_raw!r}")
        self.address = normalized
        self.local, self.domain = normalized.split("@", 1)


@dataclass
class DateRange:
    """
    Inclusive date range with validation.

    Example:
        dr = DateRange(date(2024, 1, 1), date(2024, 3, 31))
        assert date(2024, 2, 15) in dr
        print(dr.days)   # 91
    """
    start: date
    end:   date

    def __post_init__(self) -> None:
        if self.end < self.start:
            raise ValueError(f"end ({self.end}) must be >= start ({self.start})")

    def __contains__(self, d: date) -> bool:
        return self.start <= d <= self.end

    @property
    def days(self) -> int:
        return (self.end - self.start).days + 1

    def overlaps(self, other: DateRange) -> bool:
        return self.start <= other.end and other.start <= self.end


@dataclass
class Money:
    """
    Decimal money value with currency.

    Example:
        price = Money(9.99, "USD")
        total = price.add(Money(2.50, "USD"))
        print(str(total))  # "USD 12.49"
    """
    amount:   float
    currency: str = "USD"

    def __post_init__(self) -> None:
        if len(self.currency) != 3:
            raise ValueError(f"currency must be 3-letter ISO code, got {self.currency!r}")
        self.amount = round(self.amount, 2)

    def add(self, other: Money) -> Money:
        if self.currency != other.currency:
            raise ValueError(f"Cannot add {self.currency} and {other.currency}")
        return Money(self.amount + other.amount, self.currency)

    def __str__(self) -> str:
        return f"{self.currency} {self.amount:.2f}"


# ─────────────────────────────────────────────────────────────────────────────
# 3. Nested and collection fields
# ─────────────────────────────────────────────────────────────────────────────

@dataclass
class Address:
    street: str
    city:   str
    state:  str
    zip:    str
    country: str = "US"


@dataclass
class UserProfile:
    """
    Rich user model with nested and collection fields.

    Example:
        user = UserProfile(
            id=1, name="Alice", email=EmailAddress("[email protected]"),
            address=Address("123 Main St", "Springfield", "IL", "62701"),
        )
        user.tags.append("premium")
        d = asdict(user)    # fully serializable dict
    """
    id:       int
    name:     str
    email:    EmailAddress
    _:        KW_ONLY           # all fields after this are keyword-only
    address:  Address | None   = None
    tags:     list[str]        = field(default_factory=list)
    metadata: dict[str, Any]   = field(default_factory=dict)
    created:  datetime         = field(default_factory=datetime.utcnow)
    active:   bool             = True

    @property
    def display_name(self) -> str:
        return self.name.strip() or self.email.local


# ─────────────────────────────────────────────────────────────────────────────
# 4. Serialization helpers
# ─────────────────────────────────────────────────────────────────────────────

def _serialize(val: Any) -> Any:
    """Recursively serialize dataclasses and non-JSON types."""
    if is_dataclass(val) and not isinstance(val, type):
        return {k: _serialize(v) for k, v in asdict(val).items()}
    if isinstance(val, datetime):
        return val.isoformat()
    if isinstance(val, date):
        return val.isoformat()
    if isinstance(val, (list, tuple)):
        return [_serialize(v) for v in val]
    if isinstance(val, dict):
        return {k: _serialize(v) for k, v in val.items()}
    return val


def to_json(obj: Any, indent: int | None = None) -> str:
    """
    Serialize a dataclass (or nested structure) to JSON string.
    Handles datetime, date, and nested dataclasses.

    Example:
        json_str = to_json(user, indent=2)
    """
    return json.dumps(_serialize(obj), indent=indent, default=str)


def from_dict(cls, data: dict) -> Any:
    """
    Construct a (flat) dataclass from a dict, ignoring unknown keys.

    Example:
        user = from_dict(UserConfig, {"port": 8080, "debug": True, "unknown_key": "x"})
    """
    valid_keys = {f.name for f in fields(cls)}
    filtered   = {k: v for k, v in data.items() if k in valid_keys}
    return cls(**filtered)


# ─────────────────────────────────────────────────────────────────────────────
# 5. Inheritance and mixins
# ─────────────────────────────────────────────────────────────────────────────

@dataclass
class BaseEntity:
    """Base entity with auto-managed metadata."""
    id:         int
    created_at: datetime = field(default_factory=datetime.utcnow, repr=False)
    updated_at: datetime = field(default_factory=datetime.utcnow, repr=False)

    def touch(self) -> None:
        object.__setattr__(self, "updated_at", datetime.utcnow())


@dataclass
class Product(BaseEntity):
    """
    A product extending BaseEntity.

    Example:
        p = Product(id=1, name="Widget", price=Money(9.99), sku="WGT-001")
        print(p)            # Product(id=1, name='Widget', sku='WGT-001', ...)
        d = asdict(p)       # serializable dict
    """
    name:     str   = ""
    price:    Money = field(default_factory=lambda: Money(0.0))
    sku:      str   = ""
    in_stock: bool  = True
    tags:     list[str] = field(default_factory=list)


# ─────────────────────────────────────────────────────────────────────────────
# 6. Dynamic dataclass factory
# ─────────────────────────────────────────────────────────────────────────────

def schema_to_dataclass(name: str, schema: dict[str, type]) -> type:
    """
    Dynamically create a dataclass from a name → type mapping.

    Example:
        Record = schema_to_dataclass("Record", {"id": int, "name": str, "score": float})
        r = Record(id=1, name="Alice", score=0.95)
    """
    return make_dataclass(name, [(k, t) for k, t in schema.items()])


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

if __name__ == "__main__":
    print("=== dataclasses demo ===")

    print("\n--- Version (frozen, order) ---")
    v1 = Version(2, 1, 0)
    v2 = Version(2, 0, 3)
    v3 = Version.parse("1.5.2")
    print(f"  v1={v1}, v2={v2}  v1>v2: {v1 > v2}")
    print(f"  sorted: {sorted([v1, v2, v3])}")

    print("\n--- EmailAddress (InitVar, ClassVar) ---")
    email = EmailAddress("  [email protected]  ")
    print(f"  address={email.address}, domain={email.domain}")
    try:
        EmailAddress("not-an-email")
    except ValueError as e:
        print(f"  validation: {e}")

    print("\n--- DateRange ---")
    dr = DateRange(date(2024, 1, 1), date(2024, 3, 31))
    print(f"  days={dr.days}, contains 2024-02-15: {date(2024, 2, 15) in dr}")

    print("\n--- Money ---")
    price = Money(9.99)
    tax   = Money(0.80)
    print(f"  {price} + {tax} = {price.add(tax)}")

    print("\n--- UserProfile (KW_ONLY, nested, to_json) ---")
    user = UserProfile(
        id=1,
        name="Alice",
        email=EmailAddress("[email protected]"),
        address=Address("123 Main St", "Springfield", "IL", "62701"),
        tags=["premium", "beta"],
    )
    print(f"  display_name: {user.display_name}")
    j = to_json(user, indent=None)
    parsed = json.loads(j)
    print(f"  JSON keys: {list(parsed.keys())}")

    print("\n--- Product (inheritance) ---")
    p = Product(id=42, name="Widget", price=Money(19.99), sku="WGT-001")
    p.tags.append("sale")
    print(f"  {p.name}: {p.price}  sku={p.sku}  tags={p.tags}")

    print("\n--- schema_to_dataclass ---")
    Row = schema_to_dataclass("Row", {"id": int, "name": str, "score": float})
    r   = Row(id=1, name="Alice", score=0.95)
    print(f"  {r}")
    print(f"  asdict: {asdict(r)}")

    print("\n--- replace ---")
    p2 = replace(Point(1.0, 2.0), y=10.0)
    print(f"  replace: {p2}")

    print("\n--- Vector2D (slots) ---")
    v = Vector2D(3.0, 4.0)
    print(f"  length: {v.length()}  scaled: {v.scale(2.0)}")

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

For the pydantic alternative — Pydantic v2 provides runtime type validation and coercion (a string "42" is auto-coerced to int), schema generation, JSON serialization via .model_dump(), and validators as decorators — all on top of a dataclass-like definition syntax; Python dataclasses have zero-overhead validation (only what you write in __post_init__), no coercion, and are part of the standard library — use Pydantic for API input/output models where you need schema generation, automatic type coercion, and rich validators, dataclasses for internal data models, DTOs between modules, and anywhere you want typed structure without external dependencies. For the attrs alternative — attrs (@attr.s / @attr.define) provides a similar feature set to dataclasses but predates them, supports validators and converters as field-level declarative specifications, and offers deep customization of __init__, hashing, and slot behavior; Python dataclasses cover the common 80% of attrs use cases as a stdlib solution — use attrs for complex validation/converter logic at the field level or for backwards-compatible Python 2.7 projects, dataclasses for new code in Python 3.7+ where stdlib-only is preferred. The Claude Skills 360 bundle includes dataclasses skill sets covering Point/Version/Vector2D simple models, EmailAddress/DateRange/Money validated models with __post_init__, UserProfile with KW_ONLY/nested/collection fields, BaseEntity/Product inheritance, to_json()/from_dict() serialization helpers, and schema_to_dataclass() dynamic factory. Start with the free tier to try typed data modeling and dataclass 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