Claude Code for attrs: Python Classes Without Boilerplate — Claude Skills 360 Blog
Blog / AI / Claude Code for attrs: Python Classes Without Boilerplate
AI

Claude Code for attrs: Python Classes Without Boilerplate

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

attrs generates Python class boilerplate from field annotations. pip install attrs. Modern API: from attrs import define, field, Factory. @define class User: name: str; email: str; role: str = "user". Auto-generates __init__, __repr__, __eq__, __hash__. Field: age: int = field(default=0). Validator: name: str = field(validator=attrs.validators.instance_of(str)). Multiple validators: field(validator=[instance_of(str), min_len]). Custom validator: @name.validator def check_name(self, attribute, value): if not value: raise ValueError("name required"). Converter: email: str = field(converter=str.lower). age: int = field(converter=int). Factory: tags: list = field(factory=list). items: list = field(default=Factory(list)). Frozen (immutable): @define(frozen=True) class Point: x: float; y: float. p = Point(1,2); p2 = attrs.evolve(p, x=3) — new instance. Slots: @define(slots=True) — faster attribute access, smaller memory. asdict(obj) — convert to dict. astuple(obj) — convert to tuple. attrs.has(cls) — check if class uses attrs. attrs.fields(cls) — list of Attribute objects. attrs.fields(User).name.name. make_class("Point", ["x","y"]) — dynamic. On __attrs_post_init__: def __attrs_post_init__(self): self._derived = self.x + self.y. Aliases: from attr import attrs as attrs_dec, attrib — older API. @attr.s(auto_attribs=True) — enable type-annotation-based field discovery. eq=False — disable equality (useful for mutable objects). order=True — enable <>/<=/>= comparison. hash=None — auto from eq/frozen. repr=False — disable repr for sensitive fields. Validators module: attrs.validators.and_(v1,v2), not_(v), optional(v), deep_iterable(member_validator), deep_mapping(key_validator, value_validator), in_(allowed_values), lt(n), le(n), gt(n), ge(n). Claude Code generates attrs domain models, validators, converters, and frozen value objects.

CLAUDE.md for attrs

## attrs Stack
- Version: attrs >= 23.2 | pip install attrs
- Define: @define class C: field: type = attrs.field(validator=..., converter=...)
- Validators: instance_of | in_ | lt/le/gt/ge | and_ | optional | deep_iterable
- Converter: field(converter=str.lower) — auto-cast on assignment/__init__
- Mutable default: field(factory=list) — never field(default=[]) footgun
- Frozen: @define(frozen=True) + attrs.evolve(obj, field=new_val) for updates
- Serialize: attrs.asdict(obj) | attrs.astuple(obj)

attrs Class Generation Pipeline

# app/domain.py — attrs domain models
from __future__ import annotations

import re
import uuid
from datetime import datetime, timezone
from decimal import Decimal
from enum import Enum
from typing import Optional

import attrs
from attrs import Factory, define, field
from attrs import validators as v


# ─────────────────────────────────────────────────────────────────────────────
# Custom validators
# ─────────────────────────────────────────────────────────────────────────────

def validate_email(instance, attribute, value: str) -> None:
    pattern = r"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$"
    if not re.match(pattern, value):
        raise ValueError(f"{attribute.name!r} must be a valid email, got {value!r}")


def validate_non_empty(instance, attribute, value: str) -> None:
    if not value.strip():
        raise ValueError(f"{attribute.name!r} must not be empty or whitespace")


def validate_sku(instance, attribute, value: str) -> None:
    if not re.match(r"^[A-Z0-9]+-\d{4,}$", value):
        raise ValueError(f"SKU must match PROD-NNNN format, got {value!r}")


# ─────────────────────────────────────────────────────────────────────────────
# Enums
# ─────────────────────────────────────────────────────────────────────────────

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


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


# ─────────────────────────────────────────────────────────────────────────────
# Value objects — frozen (immutable)
# ─────────────────────────────────────────────────────────────────────────────

@define(frozen=True)
class Money:
    """Immutable monetary amount — supports arithmetic via evolve()."""
    amount:   Decimal
    currency: str = field(default="USD", converter=str.upper)

    def __attrs_post_init__(self) -> None:
        if self.amount < 0:
            raise ValueError(f"Money.amount cannot be negative: {self.amount}")

    def add(self, other: "Money") -> "Money":
        if self.currency != other.currency:
            raise ValueError(f"Currency mismatch: {self.currency} vs {other.currency}")
        return attrs.evolve(self, amount=self.amount + other.amount)

    def multiply(self, factor: int | Decimal) -> "Money":
        return attrs.evolve(self, amount=self.amount * Decimal(str(factor)))

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


@define(frozen=True, order=True)
class Address:
    """Ordered frozen value object — supports sorting by (state, city, street)."""
    street:      str = field(validator=[v.instance_of(str), validate_non_empty])
    city:        str = field(validator=[v.instance_of(str), validate_non_empty])
    state:       str = field(converter=str.upper,
                             validator=v.matches_re(r"^[A-Z]{2}$"))
    postal_code: str = field(validator=v.matches_re(r"^\d{5}(-\d{4})?$"))
    country:     str = field(default="US", converter=str.upper)


# ─────────────────────────────────────────────────────────────────────────────
# Mutable entities
# ─────────────────────────────────────────────────────────────────────────────

@define
class User:
    """Mutable user entity — validated on construction, eq based on id."""
    id:         str  = field(factory=lambda: str(uuid.uuid4()))
    email:      str  = field(validator=[v.instance_of(str), validate_email],
                             converter=str.lower)
    first_name: str  = field(validator=[v.instance_of(str), validate_non_empty])
    last_name:  str  = field(validator=[v.instance_of(str), validate_non_empty])
    role:       UserRole = field(
        default=UserRole.USER,
        validator=v.in_(list(UserRole)),
        converter=lambda r: UserRole(r) if isinstance(r, str) else r,
    )
    is_active:  bool     = field(default=True, validator=v.instance_of(bool))
    tags:       list[str] = field(factory=list,
                                   validator=v.deep_iterable(v.instance_of(str)))
    address:    Optional[Address] = field(
        default=None,
        validator=v.optional(v.instance_of(Address)),
    )
    created_at: datetime = field(
        factory=lambda: datetime.now(timezone.utc),
        validator=v.instance_of(datetime),
    )

    def __attrs_post_init__(self) -> None:
        # Cross-field validation after all fields are set
        if not self.first_name[0].isupper():
            raise ValueError(f"first_name should start with uppercase: {self.first_name!r}")

    @property
    def full_name(self) -> str:
        return f"{self.first_name} {self.last_name}"

    def promote_to_admin(self) -> None:
        self.role = UserRole.ADMIN


@define
class Product:
    sku:       str     = field(validator=[v.instance_of(str), validate_sku])
    name:      str     = field(validator=[v.instance_of(str), validate_non_empty])
    price:     Money
    stock:     int     = field(default=0, validator=[v.instance_of(int), v.ge(0)])
    category:  str     = field(validator=v.in_(["Electronics","Clothing","Books","Home","Sports"]))
    is_active: bool    = True
    id:        str     = field(factory=lambda: str(uuid.uuid4()))
    tags:      list[str] = field(factory=list)

    def reserve(self, quantity: int) -> None:
        if quantity > self.stock:
            raise ValueError(f"Cannot reserve {quantity} — only {self.stock} in stock")
        self.stock -= quantity

    def restock(self, quantity: int) -> None:
        if quantity < 1:
            raise ValueError(f"Restock quantity must be positive: {quantity}")
        self.stock += quantity


@define(eq=False)   # entity equality uses id, not field values
class OrderLine:
    product_id: str
    sku:        str
    quantity:   int   = field(validator=[v.instance_of(int), v.ge(1)])
    unit_price: Money

    @property
    def subtotal(self) -> Money:
        return self.unit_price.multiply(self.quantity)


@define(eq=False)
class Order:
    id:         str         = field(factory=lambda: str(uuid.uuid4()))
    user_id:    str
    lines:      list[OrderLine] = field(factory=list)
    status:     OrderStatus     = OrderStatus.PENDING
    notes:      Optional[str]   = None
    created_at: datetime        = field(factory=lambda: datetime.now(timezone.utc))

    @property
    def total(self) -> Money:
        if not self.lines:
            return Money(Decimal("0"))
        total = self.lines[0].subtotal
        for line in self.lines[1:]:
            total = total.add(line.subtotal)
        return total

    def add_line(self, line: OrderLine) -> None:
        self.lines.append(line)

    def cancel(self) -> None:
        if self.status in (OrderStatus.SHIPPED, OrderStatus.DELIVERED):
            raise ValueError("Cannot cancel a shipped or delivered order")
        self.status = OrderStatus.CANCELLED


# ─────────────────────────────────────────────────────────────────────────────
# Serialization with asdict / astuple
# ─────────────────────────────────────────────────────────────────────────────

def user_to_dict(user: User) -> dict:
    """Convert User to a JSON-serializable dict."""
    d = attrs.asdict(user)
    d["role"]       = user.role.value
    d["created_at"] = user.created_at.isoformat()
    if user.address:
        d["address"] = attrs.asdict(user.address)
    return d


if __name__ == "__main__":
    # Create user — validators run automatically
    alice = User(
        email="[email protected]",    # converter lowercases to [email protected]
        first_name="Alice",
        last_name="Smith",
        role="admin",                 # converter converts str → UserRole.ADMIN
        address=Address(
            street="123 Main St",
            city="Springfield",
            state="il",               # converter uppercases to IL
            postal_code="62701",
        ),
    )
    print(f"User: {alice.full_name} <{alice.email}> role={alice.role.value}")
    print(f"Address: {alice.address.city}, {alice.address.state}")

    # Frozen Money value object
    price = Money(Decimal("19.99"))
    tax   = Money(Decimal("1.60"))
    total = price.add(tax)
    print(f"\nPrice: {price}")
    print(f"Total with tax: {total}")

    # Evolve — new instance, original unchanged
    doubled = price.multiply(2)
    print(f"Doubled: {doubled}")

    # Order
    order = Order(user_id=alice.id)
    line  = OrderLine(
        product_id="prod-001",
        sku="BOOK-1001",
        quantity=3,
        unit_price=Money(Decimal("9.99")),
    )
    order.add_line(line)
    print(f"\nOrder total: {order.total}")

    # Serialize
    data = user_to_dict(alice)
    print(f"\nSerialized keys: {list(data.keys())}")

For the dataclasses alternative — Python dataclasses generate __init__, __repr__, and __eq__ but have no validator or converter hooks: @dataclass class User: email: str accepts any string without validation, and field(default_factory=list) is the only way to avoid the mutable-default footgun, while attrs’s field(converter=str.lower, validator=[instance_of(str), validate_email]) enforces the email format on construction and normalises case in one line. For the Pydantic BaseModel alternative — Pydantic is primarily a parsing and serialization library where instances are semi-frozen after creation, while attrs@define(eq=False) creates a fully mutable entity whose identity is its id field (not field equality), attrs.evolve(frozen_obj, x=new_val) creates a modified copy of a frozen value object without mutating the original, and @define(slots=True) uses __slots__ to reduce memory usage for high-volume domain objects by 20–40%. The Claude Skills 360 bundle includes attrs skill sets covering @define vs @attrs/attr.s, field validators and converters, Factory for mutable defaults, frozen value objects with evolve, slots optimization, attrs_post_init for cross-field validation, asdict/astuple serialization, deep_iterable and optional validators, make_class for dynamic classes, and eq=False for identity-based entities. Start with the free tier to try domain modeling 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