Skip to content

PydanticClassDeclaration

Renders a Python class that subclasses Pydantic’s BaseModel: class Name(BaseModel): ....

When bases is omitted, the class extends pydanticModule["."].BaseModel. Pass bases to inherit from another generated class (or to combine bases explicitly).

Optional modelConfig={{...}} and top-level config props (for example frozen, strict, extra) emit model_config = ConfigDict(...) for common Pydantic v2 model settings (see PydanticModelConfigDictProps). When both are used, top-level props override modelConfig keys.

Fields are ordinary class body declarations; use pydanticModule["."].Field in initializers when you need Field(...).

import { PydanticClassDeclaration } from "@alloy-js/python";
<PydanticClassDeclaration
aliasGenerator="string"
arbitraryTypesAllowed
bases={Children[]}
coerceNumbersToStr
decorators={Children[]}
extra={"allow" | "forbid" | "ignore"}
fromAttributes
frozen
hideInputInErrors
jsonSchemaExtra={Record<string, unknown>}
locByAlias
modelConfig={PydanticModelConfigDictProps}
modelConfigExpression={Children}
populateByName
revalidateInstances={"always" | "never" | "subclass-instances"}
serJsonBytes={"utf8" | "base64" | "hex"}
serJsonInfNan={"null" | "constants" | "strings"}
strMaxLength={number}
strMinLength={number}
strStripWhitespace
strToLower
strToUpper
strict
useEnumValues
valJsonBytes={"utf8" | "base64" | "hex"}
validateAssignment
validateDefault
validateReturn
/>
aliasGeneratoroptional stringResolve field aliases from a configured alias generator.
arbitraryTypesAllowedoptional booleanAllow non-pydantic/arbitrary Python types in field annotations.
basesoptional Children[]The base classes that this class inherits from.
coerceNumbersToStroptional booleanCoerce numeric input values to strings for str fields.
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.
extraoptional “allow” | “forbid” | “ignore”Behavior for unknown input keys: allow, forbid, or ignore.
fromAttributesoptional booleanPopulate models from object attributes (ORM-style) instead of mapping keys.
frozenoptional booleanMake models immutable (frozen=True).
hideInputInErrorsoptional booleanHide input values in validation error messages.
jsonSchemaExtraoptional Record<string, unknown>Include JSON schema extras via a plain JSON-serializable object.
locByAliasoptional booleanUse aliases in error locations instead of field names.
modelConfigoptional PydanticModelConfigDictPropsCanonical structured config object for ConfigDict(...). Values here are merged with top-level config props. Top-level config props take precedence over modelConfig when the same key is provided in both places.
modelConfigExpressionoptional ChildrenEmits model_config = <expression> verbatim (use for arbitrary ConfigDict kwargs or dynamic config). Takes precedence over both modelConfig and top-level config props.
populateByNameoptional booleanAllow population by field name even when aliases are defined.
revalidateInstancesoptional “always” | “never” | “subclass-instances”Re-validate model/dataclass instances on assignment boundaries.
serJsonBytesoptional “utf8” | “base64” | “hex”JSON serialization format for bytes values.
serJsonInfNanoptional “null” | “constants” | “strings”JSON serialization behavior for Infinity/NaN values.
strMaxLengthoptional numberUpper-bound for constrained string lengths at model level.
strMinLengthoptional numberLower-bound for constrained string lengths at model level.
strStripWhitespaceoptional booleanStrip leading/trailing whitespace from all str fields.
strToLoweroptional booleanConvert all str values to lowercase.
strToUpperoptional booleanConvert all str values to uppercase.
strictoptional booleanEnable strict validation globally for the model.
useEnumValuesoptional booleanUse enum .value instead of enum instances during serialization.
valJsonBytesoptional “utf8” | “base64” | “hex”JSON validation format for bytes values.
validateAssignmentoptional booleanRe-validate when attributes are assigned after model creation.
validateDefaultoptional booleanValidate default values in addition to provided input values.
validateReturnoptional booleanValidate return values for call validators.
import { pydanticModule } from "@alloy-js/python";
import * as py from "@alloy-js/python";

<py.PydanticClassDeclaration name="User" frozen>
  <py.VariableDeclaration instanceVariable omitNone name="id" type="int" />
  <py.VariableDeclaration
    instanceVariable
    name="name"
    type="str"
    initializer={"Field(default=\"anonymous\")"}
  />
</py.PydanticClassDeclaration>
from pydantic import BaseModel
from pydantic import ConfigDict
from pydantic import Field

class User(BaseModel):
    model_config = ConfigDict(frozen=True)
    id: int
    name: str = Field(default="anonymous")