Cursor rule for Python dataclasses covering safe defaults, frozen value objects, slots, kw_only, __post_init__ checks, generated ordering and dict conversion.
.cursor/rules/python-data-classes.mdc. Downloaded files need to be placed in that repository path.---
description: "Cursor rule for Python dataclasses covering safe defaults, frozen value objects, slots, kw_only, __post_init__ checks, generated ordering and dict conversion."
globs: "**/*"
alwaysApply: false
---
# Python Data Classes
Applies to: Python modules that define plain data containers with `@dataclass` (value objects, config records, DTOs that cross module boundaries).
Version baseline: checked against the Python 3.15 `dataclasses` docs. `slots=True` and `kw_only=True` need Python 3.10+. Read `requires-python` before using them.
## Choose the right tool
- Use `@dataclass` for internal data containers with typed fields.
- Use Pydantic models or attrs validators instead when the data comes from untrusted input (HTTP bodies, files, environment variables) and needs parsing or coercion. Dataclasses do not validate types at runtime.
- Use `typing.NamedTuple` only when tuple behaviour (unpacking, indexing) is actually wanted.
## Defaults
- Never use a mutable default directly. `items: list[str] = []` raises `ValueError` at class creation. Use `field(default_factory=list)`.
- Exclude derived or cached fields from `__init__` with `field(init=False)`, and from equality or repr with `compare=False` / `repr=False`. For example, hide secrets with `repr=False`.
## Immutability and memory
- Use `frozen=True` for value objects and dictionary keys. Assigning to a field then raises `dataclasses.FrozenInstanceError`, and the class gets a `__hash__`. "Change" a frozen instance with `dataclasses.replace(obj, field=new)`.
- `frozen=True` is shallow. A `list` field can still be mutated. Use `tuple` or `frozenset` for collection fields of value objects.
- Use `slots=True` for classes with many instances. It prevents adding new attributes and lowers per-instance memory. Measure before claiming a gain.
- Use `kw_only=True` when a class has more than a few fields, or when fields with defaults must precede fields without them.
## Validation with __post_init__
`__post_init__` runs after the generated `__init__`. Use it for invariants and normalisation. In a frozen class, set attributes with `object.__setattr__`.
```python
from dataclasses import dataclass, field, replace, asdict
@dataclass(frozen=True, slots=True, kw_only=True)
class Money:
amount_cents: int
currency: str = "USD"
def __post_init__(self) -> None:
if self.amount_cents < 0:
raise ValueError("amount_cents must be >= 0")
object.__setattr__(self, "currency", self.currency.upper())
@dataclass(slots=True)
class Cart:
owner_id: str
items: list[str] = field(default_factory=list)
total: Money = field(default_factory=lambda: Money(amount_cents=0))
price = Money(amount_cents=1999, currency="eur")
discounted = replace(price, amount_cents=1499) # new object; price unchanged
```
## Comparison and ordering
- Do not hand-write `__eq__` or ordering methods. `@dataclass` generates `__eq__` by default (`eq=True`). Pass `order=True` to generate `<`, `<=`, `>`, `>=`. These compare fields in definition order as tuples, so put the sort key first or exclude other fields with `compare=False`.
## Inheritance
- Subclass fields are appended after base class fields. A base class field with a default followed by a subclass field without one raises `TypeError`. Use `kw_only=True` on either class, or give the new field a default.
- Keep inheritance shallow. Prefer composition (a dataclass field holding another dataclass).
## Converting to and from dicts
- `dataclasses.asdict(obj)` recursively converts nested dataclasses, lists and dicts. It deep-copies values, which is slow for big objects. Use `astuple` for tuples.
- Building from a dict: `Cart(**data)` works only for flat, trusted data. Nested dataclasses are not rebuilt automatically. For untrusted or nested input, write an explicit `from_dict` classmethod, or use Pydantic's `TypeAdapter(MyDataclass).validate_python(data)` if the project already depends on Pydantic.
## Verify before finishing
- Run the type checker the project uses (`mypy` or `pyright`). Both understand dataclass-generated `__init__` signatures.
- Add tests for each `__post_init__` invariant (an invalid value raises `ValueError`), for frozen assignment raising `FrozenInstanceError`, and for an `asdict` round trip.
Cursor rules for Next.js 14+ App Router projects updated for Next.js 16 with async params, validated Route Handlers, generateMetadata and proxy.ts in place of middleware.
Cursor rules for strict TypeScript: compiler checks beyond strict, interfaces vs type aliases, real type guards, discriminated unions, utility types and branded IDs.
Cursor rules for Tailwind CSS v4: automatic class sorting, mobile-first breakpoints, CVA variants with merging, class-based dark mode via @custom-variant, and CSS-first @theme configuration.
Cursor
language
Illustrative input and expected result. This example is a verification guide, not a recorded model run.
Content reviewed .
A developer is replacing ad-hoc dicts with typed records in a Python 3.10+ codebase and wants Cursor to generate dataclasses that are safe to share and compare.
Create a Money value object (amount_cents int >= 0, currency 3-letter code defaulting to USD and stored upper-case) and a Cart with owner_id and a list of item ids. Money must be usable as a dict key. requires-python >= 3.11.
Illustrative; not a recorded model run. Money is declared with @dataclass(frozen=True, slots=True, kw_only=True). Its __post_init__ raises ValueError for negative amounts and upper-cases currency via object.__setattr__. Cart uses field(default_factory=list). There are no hand-written __eq__ or __hash__ methods, and price changes use dataclasses.replace. The answer notes that dataclasses do not validate types for untrusted input. Tests cover the ValueError, FrozenInstanceError and the asdict round trip.
Cursor applies project rules stored as .mdc files in .cursor/rules. Each rule's frontmatter (description, globs, alwaysApply) decides whether it is always included, attached to matching files, chosen by the agent from its description, or only used when you @-mention it. Cursor also reads AGENTS.md in the project root and subdirectories for plain-Markdown instructions.
.cursor/rules/python-data-classes.mdcStarting point, not a tested configuration for your repository. Attached when files matching the globs are in context (alwaysApply: false with globs). Review the instructions, adapt the file paths and run your project's existing checks.
---
description: "Python Data Classes: frozen, slots, kw_only, default_factory and Validation project conventions"
globs: "**/*"
alwaysApply: false
---
# Python Data Classes
Applies to: Python modules that define plain data containers with `@dataclass` (value objects, config records, DTOs that cross module boundaries).
Version baseline: checked against the Python 3.15 `dataclasses` docs. `slots=True` and `kw_only=True` need Python 3.10+. Read `requires-python` before using them.
## Choose the right tool
- Use `@dataclass` for internal data containers with typed fields.
- Use Pydantic models or attrs validators instead when the data comes from untrusted input (HTTP bodies, files, environment variables) and needs parsing or coercion. Dataclasses do not validate types at runtime.
- Use `typing.NamedTuple` only when tuple behaviour (unpacking, indexing) is actually wanted.
## Defaults
- Never use a mutable default directly. `items: list[str] = []` raises `ValueError` at class creation. Use `field(default_factory=list)`.
- Exclude derived or cached fields from `__init__` with `field(init=False)`, and from equality or repr with `compare=False` / `repr=False`. For example, hide secrets with `repr=False`.
## Immutability and memory
- Use `frozen=True` for value objects and dictionary keys. Assigning to a field then raises `dataclasses.FrozenInstanceError`, and the class gets a `__hash__`. "Change" a frozen instance with `dataclasses.replace(obj, field=new)`.
- `frozen=True` is shallow. A `list` field can still be mutated. Use `tuple` or `frozenset` for collection fields of value objects.
- Use `slots=True` for classes with many instances. It prevents adding new attributes and lowers per-instance memory. Measure before claiming a gain.
- Use `kw_only=True` when a class has more than a few fields, or when fields with defaults must precede fields without them.
## Validation with __post_init__
`__post_init__` runs after the generated `__init__`. Use it for invariants and normalisation. In a frozen class, set attributes with `object.__setattr__`.
```python
from dataclasses import dataclass, field, replace, asdict
@dataclass(frozen=True, slots=True, kw_only=True)
class Money:
amount_cents: int
currency: str = "USD"
def __post_init__(self) -> None:
if self.amount_cents < 0:
raise ValueError("amount_cents must be >= 0")
object.__setattr__(self, "currency", self.currency.upper())
@dataclass(slots=True)
class Cart:
owner_id: str
items: list[str] = field(default_factory=list)
total: Money = field(default_factory=lambda: Money(amount_cents=0))
price = Money(amount_cents=1999, currency="eur")
discounted = replace(price, amount_cents=1499) # new object; price unchanged
```
## Comparison and ordering
- Do not hand-write `__eq__` or ordering methods. `@dataclass` generates `__eq__` by default (`eq=True`). Pass `order=True` to generate `<`, `<=`, `>`, `>=`. These compare fields in definition order as tuples, so put the sort key first or exclude other fields with `compare=False`.
## Inheritance
- Subclass fields are appended after base class fields. A base class field with a default followed by a subclass field without one raises `TypeError`. Use `kw_only=True` on either class, or give the new field a default.
- Keep inheritance shallow. Prefer composition (a dataclass field holding another dataclass).
## Converting to and from dicts
- `dataclasses.asdict(obj)` recursively converts nested dataclasses, lists and dicts. It deep-copies values, which is slow for big objects. Use `astuple` for tuples.
- Building from a dict: `Cart(**data)` works only for flat, trusted data. Nested dataclasses are not rebuilt automatically. For untrusted or nested input, write an explicit `from_dict` classmethod, or use Pydantic's `TypeAdapter(MyDataclass).validate_python(data)` if the project already depends on Pydantic.
## Verify before finishing
- Run the type checker the project uses (`mypy` or `pyright`). Both understand dataclass-generated `__init__` signatures.
- Add tests for each `__post_init__` invariant (an invalid value raises `ValueError`), for frozen assignment raising `FrozenInstanceError`, and for an `asdict` round trip.
Ask for a small change to one matching file. Check the tool's loaded context or instruction view, inspect the diff for the requested convention, and run the relevant build or test. A well-formatted file does not guarantee the model follows every instruction.
Cursor's docs recommend keeping individual rules under 500 lines and splitting large rules into composable ones. Cursor's documentation states that it supports AGENTS.md in the project root and in subdirectories. Use AGENTS.md for plain-Markdown instructions you also want other tools to read, and .mdc rules when you need Cursor's scoping options (globs, description-based selection, always-apply).
Documentation checked 2026-11-05: Cursor docs: Rules
Cursor rules for Next.js 14+ App Router projects updated for Next.js 16 with async params, validated Route Handlers, generateMetadata and proxy.ts in place of middleware.
Cursor rules for strict TypeScript: compiler checks beyond strict, interfaces vs type aliases, real type guards, discriminated unions, utility types and branded IDs.
Cursor rules for Tailwind CSS v4: automatic class sorting, mobile-first breakpoints, CVA variants with merging, class-based dark mode via @custom-variant, and CSS-first @theme configuration.