Claude Code for dacite: Dict to Dataclass Conversion — Claude Skills 360 Blog
Blog / AI / Claude Code for dacite: Dict to Dataclass Conversion
AI

Claude Code for dacite: Dict to Dataclass Conversion

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

dacite converts plain dicts to Python dataclasses. pip install dacite. Convert: from dacite import from_dict, Config. user = from_dict(User, {"name":"Alice","age":30}). Nested: from_dict(Order, {"id":1,"user":{"name":"Alice"}}) — recurses into User automatically. Optional: from_dict(User, {"name":"Alice"}) — missing Optional fields become None. Union: from_dict(Event, data) — dacite tries each Union member in order. Config: from_dict(User, data, Config(type_hooks={datetime: datetime.fromisoformat})) — apply a callable to transform raw values before type checking. Cast: Config(cast=[Enum]) — auto-cast str → Enum members. Config(cast=[int, float]) — auto-cast numeric strings. Strict: Config(strict=True) — raise UnexpectedDataError on unknown keys. Config(strict_unions_match=True) — require exactly one Union branch to match. Forward refs: Config(forward_references={"User": User}) — resolve string annotations in dataclass fields. Config(check_types=False) — skip runtime type checking (faster, less safe). Errors: dacite.exceptions.WrongTypeError, MissingValueError, UnionMatchError, UnexpectedDataError — all inherit from DaciteError. Remap keys: there is no built-in data_key; preprocess the dict with a rename step before calling from_dict. make_dataclass from stdlib: from dataclasses import make_dataclass; DynCls = make_dataclass("Point", [("x",float),("y",float)]). Then from_dict(DynCls, {"x":1.0,"y":2.0}). Nested list: lines: list[OrderLine] — dacite structures each element. Nested dict values: tags: dict[str,int] — dict with typed values is passed through. Claude Code generates dacite from_dict calls, Config type_hooks, and nested dataclass pipelines.

CLAUDE.md for dacite

## dacite Stack
- Version: dacite >= 1.8 | pip install dacite
- Convert: from_dict(TargetClass, dict_data, Config(...))
- Nested: automatic — dacite recurses into nested dataclass fields
- Type hooks: Config(type_hooks={datetime: datetime.fromisoformat, Decimal: Decimal})
- Cast: Config(cast=[MyEnum, int]) — auto-coerce raw values to target type
- Strict: Config(strict=True) — raise on unexpected keys from API payloads
- Errors: WrongTypeError | MissingValueError | UnionMatchError — all DaciteError

dacite Dict-to-Dataclass Pipeline

# app/deserialization.py — dacite from_dict usage
from __future__ import annotations

import uuid
from dataclasses import dataclass, field
from datetime import datetime, timezone
from decimal import Decimal
from enum import Enum
from typing import Optional, Union
from uuid import UUID

from dacite import Config, from_dict
from dacite.exceptions import (
    DaciteError,
    MissingValueError,
    UnexpectedDataError,
    UnionMatchError,
    WrongTypeError,
)


# ─────────────────────────────────────────────────────────────────────────────
# Domain models
# ─────────────────────────────────────────────────────────────────────────────

class UserRole(str, Enum):
    USER      = "user"
    MODERATOR = "moderator"
    ADMIN     = "admin"


class OrderStatus(str, Enum):
    PENDING   = "pending"
    PAID      = "paid"
    SHIPPED   = "shipped"
    DELIVERED = "delivered"
    CANCELLED = "cancelled"


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


@dataclass
class User:
    id:         str          # keep as str — UUID parsing via type_hook
    email:      str
    first_name: str
    last_name:  str
    role:       UserRole        = UserRole.USER
    is_active:  bool            = True
    address:    Optional[Address] = None
    created_at: Optional[datetime] = None


@dataclass
class OrderLine:
    product_id: str
    sku:        str
    quantity:   int
    unit_price: Decimal


@dataclass
class Order:
    id:         str
    user_id:    str
    lines:      list[OrderLine]
    status:     OrderStatus       = OrderStatus.PENDING
    notes:      Optional[str]     = None
    created_at: Optional[datetime] = None


# ─────────────────────────────────────────────────────────────────────────────
# 1. Base Config — type hooks for common types
# ─────────────────────────────────────────────────────────────────────────────

BASE_CONFIG = Config(
    type_hooks={
        datetime: datetime.fromisoformat,
        Decimal:  Decimal,
    },
    cast=[UserRole, OrderStatus],   # auto-coerce "admin" str → UserRole.ADMIN
)

STRICT_CONFIG = Config(
    type_hooks=BASE_CONFIG.type_hooks,
    cast=BASE_CONFIG.cast,
    strict=True,   # raise UnexpectedDataError on unknown fields
)


# ─────────────────────────────────────────────────────────────────────────────
# 2. Simple structure helpers
# ─────────────────────────────────────────────────────────────────────────────

def user_from_dict(data: dict) -> User:
    """
    from_dict recurses into nested dataclasses automatically:
      - data["address"] → Address instance (or None if absent/None)
      - data["role"]    → UserRole enum via cast=[UserRole]
      - data["created_at"] → datetime via type_hooks
    """
    return from_dict(User, data, BASE_CONFIG)


def order_from_dict(data: dict) -> Order:
    """
    Recursively structures the list[OrderLine] field:
      - data["lines"] is a list[dict] → each element structured as OrderLine
      - data["status"] str → OrderStatus via cast
    """
    return from_dict(Order, data, BASE_CONFIG)


def address_from_dict(data: dict) -> Address:
    return from_dict(Address, data, BASE_CONFIG)


# ─────────────────────────────────────────────────────────────────────────────
# 3. Strict mode — reject payloads with unexpected keys
# ─────────────────────────────────────────────────────────────────────────────

def user_from_api_payload(raw: dict) -> User:
    """
    Use STRICT_CONFIG for external API payloads to catch schema drift.
    UnexpectedDataError is raised if the API sends a key the dataclass lacks.
    """
    # Rename camelCase keys before passing to dacite (dacite has no data_key)
    normalized = {
        **raw,
        "first_name": raw.pop("firstName", raw.get("first_name", "")),
        "last_name":  raw.pop("lastName",  raw.get("last_name",  "")),
    }
    return from_dict(User, normalized, STRICT_CONFIG)


# ─────────────────────────────────────────────────────────────────────────────
# 4. Union type resolution
# ─────────────────────────────────────────────────────────────────────────────

@dataclass
class UserCreatedEvent:
    type:     str
    event_id: str
    user_id:  str
    email:    str


@dataclass
class OrderPlacedEvent:
    type:     str
    event_id: str
    order_id: str
    user_id:  str
    total:    Decimal


@dataclass
class PaymentReceivedEvent:
    type:     str
    event_id: str
    order_id: str
    amount:   Decimal
    currency: str


DomainEvent = Union[UserCreatedEvent, OrderPlacedEvent, PaymentReceivedEvent]

_EVENT_TYPE_MAP: dict[str, type] = {
    "user_created":     UserCreatedEvent,
    "order_placed":     OrderPlacedEvent,
    "payment_received": PaymentReceivedEvent,
}


def decode_event(data: dict) -> DomainEvent:
    """
    dacite tries each Union branch in declaration order — fragile for payloads
    with shared fields. Use an explicit type-tag dispatch instead.
    """
    event_type = data.get("type")
    cls = _EVENT_TYPE_MAP.get(event_type)
    if cls is None:
        raise ValueError(f"Unknown event type: {event_type!r}")
    return from_dict(cls, data, BASE_CONFIG)


# ─────────────────────────────────────────────────────────────────────────────
# 5. Error handling — DaciteError subtypes
# ─────────────────────────────────────────────────────────────────────────────

def safe_user_from_dict(data: dict) -> tuple[Optional[User], list[str]]:
    """
    Returns (User, []) on success or (None, [error_strings]) on failure.
    Note: dacite raises on the FIRST error — it does not collect all errors.
    Use cattrs or marshmallow for bulk error collection.
    """
    try:
        return from_dict(User, data, BASE_CONFIG), []
    except MissingValueError as exc:
        return None, [f"Missing required field: {exc.field_path}"]
    except WrongTypeError as exc:
        return None, [f"Wrong type for '{exc.field_path}': expected {exc.field_type}, got {type(exc.field_data).__name__}"]
    except UnexpectedDataError as exc:
        return None, [f"Unexpected fields: {exc.keys}"]
    except UnionMatchError as exc:
        return None, [f"No Union branch matched for '{exc.field_path}'"]
    except DaciteError as exc:
        return None, [str(exc)]


# ─────────────────────────────────────────────────────────────────────────────
# 6. Batch structuring from a list of dicts
# ─────────────────────────────────────────────────────────────────────────────

def users_from_list(rows: list[dict]) -> list[User]:
    """Structure a list of dicts in one pass — no schema object needed."""
    return [from_dict(User, row, BASE_CONFIG) for row in rows]


def orders_from_list(rows: list[dict]) -> list[Order]:
    return [from_dict(Order, row, BASE_CONFIG) for row in rows]


# ─────────────────────────────────────────────────────────────────────────────
# 7. check_types=False — fast path for pre-validated data
# ─────────────────────────────────────────────────────────────────────────────

FAST_CONFIG = Config(
    type_hooks=BASE_CONFIG.type_hooks,
    cast=BASE_CONFIG.cast,
    check_types=False,   # skip isinstance checks — ~2× faster, less safe
)


def user_from_trusted_source(data: dict) -> User:
    """
    Use when data comes from a database layer that already guarantees types.
    Skips type validation — do NOT use for untrusted external input.
    """
    return from_dict(User, data, FAST_CONFIG)


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

if __name__ == "__main__":
    # Basic nested structure
    raw_user = {
        "id":         "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
        "email":      "[email protected]",
        "first_name": "Alice",
        "last_name":  "Smith",
        "role":       "admin",                     # str → UserRole.ADMIN via cast
        "created_at": "2024-01-15T10:30:00+00:00", # str → datetime via type_hook
        "address": {
            "street":      "123 Main St",
            "city":        "Springfield",
            "state":       "IL",
            "postal_code": "62701",
        },
    }

    user = user_from_dict(raw_user)
    print(f"User: {user.first_name} {user.last_name}")
    print(f"  role:      {user.role} (type={type(user.role).__name__})")
    print(f"  created:   {user.created_at.isoformat()}")
    print(f"  city:      {user.address.city}")

    # Order with nested lines
    raw_order = {
        "id":      "ord-001",
        "user_id": raw_user["id"],
        "status":  "paid",
        "lines": [
            {"product_id": "prod-1", "sku": "PROD-1001", "quantity": 2, "unit_price": "19.99"},
            {"product_id": "prod-2", "sku": "BOOK-2005", "quantity": 1, "unit_price": "39.99"},
        ],
    }
    order = order_from_dict(raw_order)
    print(f"\nOrder: {order.id} status={order.status.value}")
    print(f"  lines: {len(order.lines)}")
    print(f"  total: {sum(l.unit_price * l.quantity for l in order.lines)}")

    # Error handling — missing required field
    bad_user = {"id": "x", "email": "[email protected]", "last_name": "Smith"}
    result, errors = safe_user_from_dict(bad_user)
    print(f"\nValidation error: {errors[0]}")

    # Union / event dispatch
    event_dict = {
        "type":     "order_placed",
        "event_id": "evt-123",
        "order_id": "ord-001",
        "user_id":  "usr-456",
        "total":    "79.97",
    }
    event = decode_event(event_dict)
    print(f"\nEvent: {type(event).__name__}")
    print(f"  total: {event.total} ({type(event.total).__name__})")

    # Optional field absent — becomes None, no error
    minimal = {"id": "x", "email": "[email protected]", "first_name": "Bob", "last_name": "Jones"}
    u2 = user_from_dict(minimal)
    print(f"\nMinimal user: address={u2.address} created_at={u2.created_at}")

    # Unexpected key with STRICT_CONFIG
    try:
        from_dict(User, {**minimal, "unknown_field": "surprise"}, STRICT_CONFIG)
    except UnexpectedDataError as exc:
        print(f"\nStrict rejected keys: {exc.keys}")

For the cattrs alternative — cattrs’s GenConverter handles both structuring and unstructuring — converting objects back to plain dicts — while dacite only structures (dict→dataclass) and has no unstructure step, so dacite is the right choice for read-only deserialization of JSON payloads into dataclasses when you only need the inbound direction and want zero dependencies beyond the stdlib dataclasses module. For the pydantic alternative — Pydantic BaseModel validates on model_validate(dict), collects all field errors in one pass (dacite stops at the first error), and also supports serialization via model_dump(), but every model must extend BaseModel — legacy dataclasses can’t be used as-is — while dacite’s from_dict(ExistingDataclass, data) works with any @dataclass without modification, making it ideal for gradually adding type-safe deserialization to an existing codebase that already uses stdlib dataclasses. The Claude Skills 360 bundle includes dacite skill sets covering from_dict for nested dataclass construction, Config type_hooks for datetime/Decimal/UUID, cast for Enum auto-coercion, strict mode for API payload validation, Union type dispatch with explicit type-tag routing, MissingValueError/WrongTypeError/UnexpectedDataError handling, check_types=False for trusted sources, batch structuring from lists, and camelCase-to-snake_case preprocessing patterns. Start with the free tier to try dataclass deserialization 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