new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

Pydantic · API reference · all subjects

dataclasses

20 notes, read out of this brain and free to use. Each one was extracted from a source and is re-checked against its exam.

pydantic.dataclasses module overview

The pydantic.dataclasses module provides dataclass decorators and utilities for creating Pydantic-validated dataclasses. This is the API reference for the dataclasses submodule of Pydantic.

Pydantic dataclasses support configuration

Pydantic dataclasses support configuration via the config parameter in the @dataclass decorator, accepting a ConfigDict instance. Example: @dataclass(config=ConfigDict(str_max_length=10, validate_assignment=True)) class User: name: str

Pydantic dataclass decorator import and basic usage

Pydantic dataclasses are created using the @dataclass decorator from pydantic.dataclasses module. They provide the same data validation as BaseModel but work with standard dataclasses. Example: @dataclass decorates a class with typed fields that undergo validation on instantiation.

Pydantic dataclass basic example with validation

from datetime import datetime from pydantic.dataclasses import dataclass @dataclass class User: id: int name: str = 'John Doe' signup_ts: datetime | None = None user = User(id='42', signup_ts='2032-06-21T12:00') print(user) # User(id=42, name='John Doe', signup_ts=datetime.datetime(2032, 6, 21, 12, 0))

Pydantic dataclass differences from models

Pydantic dataclasses do not have the various methods to validate, dump, and generate JSON Schema that models have. Instead, you can wrap the dataclass with a TypeAdapter and make use of its methods like dump_python() and validate_python().

Using TypeAdapter with Pydantic dataclasses

from pydantic import TypeAdapter from pydantic.dataclasses import dataclass @dataclass class Foo: f: int foo = Foo(f=1) TypeAdapter(Foo).dump_python(foo) # {'f': 1} TypeAdapter(Foo).validate_python({'f': 1}) # Foo(f=1)

Pydantic dataclass with Field and dataclasses.field

from pydantic import Field import dataclasses from pydantic.dataclasses import dataclass @dataclass class User: id: int name: str = 'John Doe' friends: list[int] = dataclasses.field(default_factory=lambda: [0]) age: int | None = dataclasses.field( default=None, metadata={'title': 'The age of the user', 'description': 'do not lie!'}, ) height: int | None = Field( default=None, title='The height in cm', ge=50, le=300 )

Pydantic dataclass configuration with config parameter

The @dataclass decorator from pydantic.dataclasses accepts a config parameter that takes a ConfigDict instance to modify validation behavior, similar to BaseModel configuration.

Configuring Pydantic dataclass with __pydantic_config__ attribute

from pydantic import ConfigDict from pydantic.dataclasses import dataclass @dataclass class MyDataclass2: a: int __pydantic_config__ = ConfigDict(validate_assignment=True)

rebuild_dataclass() function

The rebuild_dataclass() function from pydantic.dataclasses can be used to rebuild the core schema of a dataclass.

Inheriting from stdlib dataclasses with Pydantic dataclass

Stdlib dataclasses (nested or not) can be inherited by Pydantic dataclasses, and Pydantic will automatically validate all the inherited fields.

Applying Pydantic dataclass decorator to stdlib dataclass

import dataclasses import pydantic @dataclasses.dataclass class A: a: int PydanticA = pydantic.dataclasses.dataclass(A) print(PydanticA(a='1')) # A(a=1)

Stdlib dataclasses validated within BaseModel with revalidate_instances

When a standard library dataclass is used as a field in a Pydantic model, validation is applied only if model_config has revalidate_instances='always'. Otherwise, a pre-existing dataclass instance is not revalidated.

Using arbitrary_types_allowed with stdlib dataclasses in models

When a stdlib dataclass with custom types is used in a Pydantic model, the ConfigDict(arbitrary_types_allowed=True) configuration must be set on the model to allow the custom types, and this configuration pushes down to nested dataclasses.

is_pydantic_dataclass() function

The is_pydantic_dataclass() function from pydantic.dataclasses can be used to check if a type is specifically a Pydantic dataclass. This returns True only for Pydantic dataclasses, whereas dataclasses.is_dataclass() returns True for both stdlib and Pydantic dataclasses.

field_validator with Pydantic dataclasses

from pydantic import field_validator from pydantic.dataclasses import dataclass @dataclass class DemoDataclass: product_id: str @field_validator('product_id', mode='before') @classmethod def convert_int_serial(cls, v): if isinstance(v, int): v = str(v).zfill(5) return v print(DemoDataclass(product_id='01234')) # DemoDataclass(product_id='01234') print(DemoDataclass(product_id=2468)) # DemoDataclass(product_id='02468')

Pydantic dataclass __post_init__ method timing

The __post_init__() method in a Pydantic dataclass is called between the calls to before and after model validators. The execution order is: before model validators, then __post_init__(), then after model validators.

model_validator with Pydantic dataclasses

from pydantic_core import ArgsKwargs from typing_extensions import Self from pydantic import model_validator from pydantic.dataclasses import dataclass @dataclass class Birth: year: int month: int day: int @dataclass class User: birth: Birth @model_validator(mode='before') @classmethod def before(cls, values: ArgsKwargs) -> ArgsKwargs: return values @model_validator(mode='after') def after(self) -> Self: return self def __post_init__(self): pass user = User(**{'birth': {'year': 1995, 'month': 3, 'day': 2}})

model_validator mode parameter for dataclasses returns ArgsKwargs

In Pydantic dataclasses, when using @model_validator(mode='before'), the values parameter is of type ArgsKwargs, unlike in Pydantic models where it would be a dictionary.

Example: detecting circular references during serialization with field_serializer

```python from dataclasses import field from typing import Any from pydantic import SerializerFunctionWrapHandler, TypeAdapter, field_serializer from pydantic.dataclasses import dataclass @dataclass class NodeReference: id: int @dataclass class Node(NodeReference): children: list['Node'] = field(default_factory=list) @field_serializer('children', mode='wrap') def serialize( self, children: list['Node'], handler: SerializerFunctionWrapHandler ) -> Any: try: return handler(children) except ValueError as exc: if not str(exc).startswith('Circular reference'): raise exc result = [] for node in children: try: serialized = handler([node]) except ValueError as exc: if not str(exc).startswith('Circular reference'): raise exc result.append({'id': node.id}) else: result.append(serialized) return result ``` This example shows how to handle circular references during serialization by using a wrap mode field_serializer to catch ValueError exceptions with 'Circular reference' message.

Give your agent this brain