Python API reference#

What a generated module exports, and what model.errors gives you to handle what validate raises.

Generated members#

The *Raw pattern#

Every generated struct and union has a *Raw counterpart: NameRaw for a struct, UnionNameRaw for a union. This is the wire shape, the type msgspec.json.decode(), msgspec.yaml.decode(), and msgspec.toml.decode() produce directly, before any model-specific normalization is applied. In particular, a non-required list or map field is typed | None on the *Raw struct, since msgspec leaves it unset rather than filling in [] or {}.

from_raw converts an already-decoded raw value into the real type, normalizing it along the way (for example, turning a None list or map into its empty value). For a struct, Name.from_raw takes a NameRaw and returns a Name directly. For a union, UnionName.from_raw takes the UnionNameRaw type alias, a union of one tagged VariantNameRaw struct per variant, and pattern-matches on which *Raw variant it received to build the matching VariantName. Each VariantNameRaw holds the variant’s value, in its own raw form, in its value field. An inlined variant’s VariantNameRaw subclasses its struct’s *Raw instead, so it has the struct’s fields and no value.

Name.decode_json, Name.decode_yaml, and Name.decode_toml are the built-in consumers of this: each decodes into NameRaw first, then calls from_raw. Code that already has a decoded raw value, such as one nested inside a larger msgspec decode, calls from_raw directly instead of decoding twice.

to_raw is the reverse of from_raw: Name.to_raw returns the NameRaw for a value, and UnionName.to_raw returns the tagged VariantNameRaw for the variant. Name.encode_json, Name.encode_yaml, and Name.encode_toml call to_raw and encode the result. Each *Raw struct sets omit_defaults=True, so an unset optional field is not encoded.

Per struct#

class Name(kw_only=True)#

Bases: msgspec.Struct

The struct you hold. A keyword-only msgspec Struct. Fields are added for each model field. Fields like map<K, V> and list<T> are always present when deserialized by the model.

See The *Raw pattern for NameRaw, from_raw, and to_raw.

field_window: tuple[time, time]#

One (from, to) for all time fields that declare a window.

classmethod decode_json(data: bytes | str) → Self#

Decode JSON into Name.

Raises:

MsgspecError

classmethod decode_yaml(data: bytes | str) → Self#

Decode YAML into Name.

Raises:

MsgspecError

classmethod decode_toml(data: bytes | str) → Self#

Decode TOML into Name.

Raises:

MsgspecError

encode_json() → bytes#

Encode Name as JSON.

encode_yaml() → bytes#

Encode Name as YAML.

encode_toml() → bytes#

Encode Name as TOML.

validate(*, file_path: PathLike = None) → None#

Check every constraint.

Raises:

ExceptionGroup of ValidationError

Per enum#

class EnumName#

Bases: IntEnum or StrEnum

One member is generated per defined value.

Per union#

class UnionNameTag#

Bases: IntEnum or StrEnum

One member is generated per variant of the union. This class is only generated is the tag type is defined as str or int instead of an existing model enum.

class UnionNameVariant#

Bases: object

One per variant of the union. These classes support positional pattern matching.

class UnionName#

Bases: object

The base class every variant subclasses.

VariantName#

One class attribute per variant.

Tag#

The class used for this union’s tag.

This acts as a universal location to access the Tag class, independent of if an existing model enum was used or an enum was generated for this union.

by_tags: Mapping[Tag, VariantName]#

A mapping of tag member to generated variant class.

See The *Raw pattern for UnionNameRaw, from_raw, and to_raw.

decode_Name(type: TypeForm)#

A msgspec dec_hook for the union.

Per Route#

At this time routes have no generated code in python.

model.errors#

Everything below is importable from model.errors.

Exceptions#

ModelError                 (Exception)
└── ValidationError
    ├── RequiredError
    └── ConstraintError
        ├── LengthError
        ├── UniqueError
        ├── RangeError
        └── ConstantError

ModelError is the base of every error this library raises. ValidationError is what a constraint failure is, and the five leaves say which kind of constraint failed. Catching ValidationError catches all of them; catching ConstraintError catches everything except a missing required value.

Model exceptions and the validation context used to collect them.

exception ModelError#

Bases: Exception

An exception in model logic.

exception ValidationError(msg: str, data_paths: list[str], file_path: str | None = None)#

Bases: ModelError

A validation exception has occurred.

data_paths: list[str]#

Where the offending value sits in the structure that was validated.

file_path: str | None = None#

The file the value came from, or None if no file is known.

exception RequiredError(msg: str, data_paths: list[str], file_path: str | None = None)#

Bases: ValidationError

A required field was not provided.

exception ConstraintError(msg: str, data_paths: list[str], file_path: str | None = None)#

Bases: ValidationError

A constraint was violated.

exception LengthError(msg: str, data_paths: list[str], file_path: str | None = None)#

Bases: ConstraintError

A length constraint was violated.

exception UniqueError(msg: str, data_paths: list[str], file_path: str | None = None)#

Bases: ConstraintError

A unique constraint was violated.

exception RangeError(msg: str, data_paths: list[str], file_path: str | None = None)#

Bases: ConstraintError

A range constraint was violated.

exception ContentTypeError(msg: str, data_paths: list[str], file_path: str | None = None)#

Bases: ConstraintError

A file’s content was not one of the types its field allows.

exception VersionError(msg: str, data_paths: list[str], file_path: str | None = None)#

Bases: ConstraintError

A UUID was not of the version its field requires.

exception ConstantError(msg: str, data_paths: list[str], file_path: str | None = None)#

Bases: ConstraintError

A constant field held a value other than its constant.

validate raises these inside an ExceptionGroup, never on their own, so read them from .exceptions:

try:
    product.validate()
except ExceptionGroup as errors:
    for error in errors.exceptions:
        print(error.data_paths, error)

model.isbn#

Generated code imports this module for an isbn field. It needs python-stdnum, which the isbn extra installs: pip install model[isbn].

model.isbn.normalize_isbn(value: str) → str#

Return the compact ISBN-13 an isbn field holds for value, an ISBN-10 or ISBN-13 whose digits hyphens or spaces may separate. from_raw calls it on every isbn value, including those in lists and maps. Call it yourself to normalize an ISBN you pass to a struct’s constructor, which checks nothing.

Raises:

msgspec.ValidationError, as decoding does, if value is not an ISBN.

model.uuids#

Generated code imports this module for a uuid field.

model.uuids.parse_uuid(value: str) → UUID#

Return the UUID a uuid field holds for value, its hyphenated hex form in either case. from_raw calls it on every uuid value, including those in lists and maps.

Raises:

msgspec.ValidationError, as decoding does, if value is not a UUID in that form.

model.url#

Generated code imports this module for a url field. It needs yarl, which the url extra installs: pip install model[url].

model.url.resolve_url(value: str, base: URL | str | None) → URL#

Return the absolute URL a url field holds for value, the wire form. With a base, value can be any URI reference, and it is resolved against base. With no base, value must be absolute. A string base is a literal base, and is parsed only once. from_raw calls this function on every url value.

Raises:

msgspec.ValidationError, as decoding does, if value is not a URI reference, or is relative and there is no base.

model.url.relative_url(value: URL, base: URL | str | None) → str#

Return the wire form of value for a field with base: relative to base when they share a scheme, user, host and port, and in full otherwise. to_raw calls this function on every url value. resolve_url of the result is value again.

model.zoned_datetime#

Generated code imports this module for a datetime field. It needs nothing beyond the standard library, but see Datetimes for the zone files.

decode_datetime(value: object) → datetime#

Return the datetime, in its own zone, that value holds: RFC 9557 text, plain RFC 3339 text, or an aware datetime, as a native TOML or YAML timestamp decodes to. A named zone is a ZoneInfo, Z is datetime.UTC, and a bare offset is a timezone fixed at it. from_raw calls this function on every datetime value, including map keys.

Raises:

msgspec.ValidationError, as decoding does, if value has no UTC offset, names an unknown zone, has an offset its zone does not have at that instant, or carries a critical annotation other than the zone.

encode_datetime(value: datetime) → str#

Return the RFC 9557 text of value, with its zone in brackets: 2026-10-06T21:00:00-04:00[America/New_York]. A zone fixed at an offset is written 2026-10-06T21:00:00-04:00[-04:00]. to_raw calls this function on every datetime value.

Raises:

ValueError if value is naive.

zone_name(value: datetime) → str#

Return the name of value’s zone as it is written in brackets: a ZoneInfo’s IANA name, UTC for datetime.UTC, and otherwise the zone’s offset at value, such as -04:00.

Raises:

ValueError if value is naive.