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.StructThe struct you hold. A keyword-only msgspec Struct. Fields are added for each model field. Fields like
map<K, V>andlist<T>are always present when deserialized by the model.See The *Raw pattern for
NameRaw,from_raw, andto_raw.
Per enum#
Per union#
- class UnionNameTag#
-
One member is generated per variant of the union. This class is only generated is the tag type is defined as
strorintinstead of an existing model enum.
- class UnionNameVariant#
Bases:
objectOne per variant of the union. These classes support positional pattern matching.
- class UnionName#
Bases:
objectThe 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.
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 ValidationError(msg: str, data_paths: list[str], file_path: str | None = None)#
Bases:
ModelErrorA validation exception has occurred.
- exception RequiredError(msg: str, data_paths: list[str], file_path: str | None = None)#
Bases:
ValidationErrorA required field was not provided.
- exception ConstraintError(msg: str, data_paths: list[str], file_path: str | None = None)#
Bases:
ValidationErrorA constraint was violated.
- exception LengthError(msg: str, data_paths: list[str], file_path: str | None = None)#
Bases:
ConstraintErrorA length constraint was violated.
- exception UniqueError(msg: str, data_paths: list[str], file_path: str | None = None)#
Bases:
ConstraintErrorA unique constraint was violated.
- exception RangeError(msg: str, data_paths: list[str], file_path: str | None = None)#
Bases:
ConstraintErrorA range constraint was violated.
- exception ContentTypeError(msg: str, data_paths: list[str], file_path: str | None = None)#
Bases:
ConstraintErrorA 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:
ConstraintErrorA UUID was not of the version its field requires.
- exception ConstantError(msg: str, data_paths: list[str], file_path: str | None = None)#
Bases:
ConstraintErrorA 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
isbnfield holds forvalue, an ISBN-10 or ISBN-13 whose digits hyphens or spaces may separate.from_rawcalls it on everyisbnvalue, 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, ifvalueis 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
uuidfield holds forvalue, its hyphenated hex form in either case.from_rawcalls it on everyuuidvalue, including those in lists and maps.- Raises:
msgspec.ValidationError, as decoding does, ifvalueis 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
urlfield holds forvalue, the wire form. With abase,valuecan be any URI reference, and it is resolved againstbase. With no base,valuemust be absolute. A stringbaseis a literal base, and is parsed only once.from_rawcalls this function on everyurlvalue.- Raises:
msgspec.ValidationError, as decoding does, ifvalueis not a URI reference, or is relative and there is no base.
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, thatvalueholds: RFC 9557 text, plain RFC 3339 text, or an awaredatetime, as a native TOML or YAML timestamp decodes to. A named zone is aZoneInfo,Zisdatetime.UTC, and a bare offset is atimezonefixed at it.from_rawcalls this function on everydatetimevalue, including map keys.- Raises:
msgspec.ValidationError, as decoding does, ifvaluehas 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 written2026-10-06T21:00:00-04:00[-04:00].to_rawcalls this function on everydatetimevalue.- Raises:
ValueErrorifvalueis naive.
- zone_name(value: datetime) str#
Return the name of
value’s zone as it is written in brackets: aZoneInfo’s IANA name,UTCfordatetime.UTC, and otherwise the zone’s offset atvalue, such as-04:00.- Raises:
ValueErrorifvalueis naive.