Skip to content

Root models and adapters

didactic.api.RootModel

RootModel(**kwargs: FieldValue | JsonValue)

Bases: Model

A Model whose value is a single typed payload.

Attributes:

Name Type Description
root T

The wrapped value. Must satisfy the type parameter T.

Examples:

>>> import didactic.api as dx
>>> class StringList(dx.RootModel[tuple[str, ...]]):
...     pass
>>> StringList(root=("a", "b")).root
('a', 'b')

didactic.api.TypeAdapter

TypeAdapter(type_: type[T])

Validate values of an arbitrary type without defining a class.

Parameters:

Name Type Description Default
type_ type[T]

The type to validate against. Must be one didactic understands (str, int, float, bool, bytes, datetime, Decimal, UUID, tuple, frozenset, dict, Optional, Literal, Annotated).

required

Examples:

>>> import didactic.api as dx
>>> adapter = dx.TypeAdapter(int)
>>> adapter.validate(42)
42
>>> adapter.validate("not an int")
Traceback (most recent call last):
...
TypeError: ...

validate

validate(value: FieldValue) -> T

Validate value against the adapter's type.

Parameters:

Name Type Description Default
value FieldValue

The value to validate.

required

Returns:

Type Description
T

The validated (and possibly coerced) value.

Raises:

Type Description
TypeError

If the value cannot be coerced to the target type.

dump_json

dump_json(value: T) -> str

Encode value to a JSON string.