Skip to content

DataclassDeclaration

Renders a Python dataclass.

Example:

<py.DataclassDeclaration name="User" kwOnly>
  <py.VariableDeclaration instanceVariable omitNone name="id" type="int" />
  <py.VariableDeclaration instanceVariable name={namekey("_", { ignoreNamePolicy: true })} type={dataclassesModule["."].KW_ONLY} omitNone />
  <py.VariableDeclaration
    instanceVariable
    name="name"
    type="str"
    initializer={"Anonymous"}
  />
</py.DataclassDeclaration>

Will render as:

from dataclasses import dataclass
from dataclasses import KW_ONLY

@dataclass(kw_only=True)
class User:
    id: int
    _: KW_ONLY
    name: str = "Anonymous"
import { DataclassDeclaration } from "@alloy-js/python";
<DataclassDeclaration bases={Children[]} decorators={Children[]} />
basesoptional Children[]The base classes that this class inherits from.
decoratorsoptional Children[]Decorators rendered above the class keyword, in source order — decorators[0] is topmost. By Python’s bottom-up application order, the topmost entry is the outermost decorator (applied last). Each entry should produce a complete decorator line (typically starting with @). Falsy entries are skipped, so conditional decorators can be provided inline when needed. Wrappers like DataclassDeclaration build their intrinsic decorator (e.g. @dataclass(...)) and append it to this list at the position that keeps @dataclass closest to the class — i.e. user decorators end up above the intrinsic one, matching how Pydantic’s @field_validator sits above @classmethod on methods. Do not pass a wrapper’s intrinsic decorator here. For example, when using DataclassDeclaration, do not include @dataclass(...) in decorators — the component renders it for you, and stacking it twice would produce invalid Python.