Python#
The Python generator emits msgspec structs. Enable it with a
[tool.model.python] table, whose only key is out:
[tool.model.python]
out = "catalog.py"
Everything in the model lands in that one module.
Dependencies#
Generated Python imports msgspec, typing_extensions,
decimal, and model.errors from this package. model is
therefore a runtime dependency of any project that consumes the Python output,
not just a build-time tool:
pip install model
A model with an isbn field also needs python-stdnum, which the generated
code uses through model.isbn. Install the isbn extra:
pip install model[isbn]
A model with a url field needs yarl, which the generated code uses through
model.url. Install the url extra:
pip install model[url]
A model with a nerd_font_glyph field needs libnerd_font, which the
generated code uses through model.nerd_font. Install the nerd_font extra:
pip install model[nerd_font]
The libnerd_font Python client loads the libnerd_font C library when it is imported, so the C library must be installed too.
Structs#
Each struct in the model becomes two classes.
class ProductRaw(Struct, kw_only=True):
"""Something the shop sells."""
sku: str
name: str
price: Decimal
tags: list[str] | None = []
class Product(Struct, kw_only=True):
"""Something the shop sells."""
sku: str
name: str
price: Decimal
tags: list[str] = []
ProductRaw is the wire shape: every non-required field can arrive as
None. Product is the type you hold, where a field that stands in
for emptiness — a list or a map — has lost the None and defaults to
[] or {} instead. That is the whole reason for the pair: absence is a fact
about the wire, not about your program.
Both are msgspec structs, and both are keyword-only.
A struct or field may share its name with something the generated file
imports. The import is then renamed instead: a field called date holding a
date is written as date: date_, with from datetime import date as date_
at the top of the file. Your names are never changed.
Decoding#
@classmethod
def decode_json(cls, data: str | bytes) -> Self
@classmethod
def decode_yaml(cls, data: str | bytes) -> Self
@classmethod
def decode_toml(cls, data: str | bytes) -> Self
@classmethod
def from_raw(cls, raw: ProductRaw) -> Self
decode_json, decode_yaml, and decode_toml read the wire form into the
Raw class and convert. from_raw is that second half on its own, for when
you already hold a decoded Raw value.
A Raw class names every struct and union it holds by its Raw class too,
and from_raw converts each through that type’s own from_raw, at any depth
and inside lists and maps. A nested struct therefore decodes exactly as it
does on its own. An empty list that arrives as null becomes [] there as
well.
A required list or map that is absent or null decodes as well, to [] or
{}, so code holding a decoded value need not guard against None.
It is validate that reports one that is empty, with a RequiredError.
A map keyed by boolean, date, time or datetime holds its keys as
Any in the Raw class, because msgspec cannot read or write them in every
format. from_raw reads each key from its text, or from a native YAML key
such as true or 2024-01-02. A boolean key also takes every spelling Go
reads, such as 1 or F. to_raw writes each key as its text: true or
false, and ISO 8601 for a date or time, as Go does. A datetime key is
read and written as a datetime value is (see Datetimes), and an
isbn key is normalized like an isbn value. A ref key is a Ref of
its target’s key, which is read and written in the same way.
product = Product.decode_json(body)
A blank value, "" of a string type, is no value: a required field holding
one is missing, and fails as an absent one does, with msgspec’s
Object missing required field error. An optional one decodes as
None. The string types are string, path, url, password,
secret, isbn, uuid, and a reference whose key is one of these. An
item of a list, or a key or value of a map, can not be absent, so a blank one is
reported as required at its path from its struct, as tags[1]. The Raw
class checks this in its __post_init__, so msgspec adds the struct’s own
path, as it does for an absent field. The zero value of any other type, such
as 0 or false, is a value.
Decoding checks types, not constraints. A sku shorter than the model’s
min_length decodes fine and fails validate.
Encoding#
def encode_json(self) -> bytes
def encode_yaml(self) -> bytes
def encode_toml(self) -> bytes
def to_raw(self) -> ProductRaw
encode_json, encode_yaml, and encode_toml are the reverse of decoding:
they convert the value to its Raw class with to_raw, then encode that. As
with from_raw, to_raw converts each nested struct and union through its
own to_raw, so a union comes out with its tag.
body = product.encode_json()
Every Raw class omits a field that holds its default, so an unset optional
field is left out rather than written as null. TOML has no null, so this
is what lets encode_toml write a value with unset fields. Decoding fills the
default back in.
Validation#
def validate(self, *, file_path: str | None = None, ctx: Context | None = None)
validate collects rather than fails fast. Called with no ctx, it gathers
every violation in the value and raises them together as one
ExceptionGroup:
try:
product.validate()
except ExceptionGroup as errors:
for error in errors.exceptions:
print(error.data_paths, error)
Constraints descend into list elements and into both the keys and the values of a map, so one call covers the whole value rather than its top level.
Pass file_path when the value came from a file and you want that recorded on
every error raised.
Passing a ctx switches the method into its other mode: it appends to that
context and raises nothing, leaving the caller to decide when to stop. That is
how a caller validates a tree of values and reports every problem in it at
once, rather than the first object’s problems:
from model.errors import ValidationContext
ctx = ValidationContext(file_path="catalog.json")
for product in products:
product.validate(ctx=ctx)
if ctx.errors:
raise ExceptionGroup("catalog is invalid", ctx.errors)
Python API reference documents the context and the error classes.
Enums#
An enum becomes an enum.IntEnum or enum.StrEnum,
chosen by the model’s tag type, with each member carrying its desc as a
docstring.
class Sample(IntEnum):
"""A sample enum"""
foo = 0
bar = 1
Unions#
A union becomes a base class, one subclass per variant, and a tag enum.
class ShapeTag(StrEnum):
Circle = "circle"
Square = "Square"
class Shape:
Tag: ClassVar[type[ShapeTag]] = ShapeTag
by_tags: ClassVar[dict[ShapeTag, type[Shape]]]
Circle: ClassVar[type[ShapeCircle]]
Square: ClassVar[type[ShapeSquare]]
@classmethod
def from_raw(cls, raw: ShapeRaw) -> Shape: ...
Each variant is reachable both as a module-level name and through the base
class, so ShapeCircle and Shape.Circle are the same class. Variants define
__match_args__, which makes them usable in a match statement:
match shape:
case Shape.Circle(inner):
...
case Shape.Square(inner):
...
by_tags maps a tag to its variant class, for dispatch driven by data rather
than by code.
Decoding a union#
Unions decode through a module-level function shaped as a msgspec
dec_hook:
def decode_Shape(type: TypeForm, obj: Any) -> object
It decodes the union’s Raw and converts it with from_raw. The
generated decode_* methods do not need it: they decode a union field through
its Raw alias and from_raw. Hand it to msgspec as the dec_hook only when
you decode a type that contains the union with msgspec yourself.
Datetimes#
A datetime field is an aware datetime, and its
tzinfo is the zone it was written in: a ZoneInfo for
a named zone. On the wire it is RFC 9557
text, the timestamp followed by the zone’s IANA name in brackets, in JSON,
YAML and TOML alike, and as a map key:
2026-10-06T21:00:00-04:00[America/New_York]
The field is Any in the Raw class, which holds that text, or the native
timestamp a TOML or YAML file may hold instead. from_raw reads it with
model.zoned_datetime.decode_datetime(), and to_raw writes it with
model.zoned_datetime.encode_datetime(), the same text Go and
TypeScript write.
A plain RFC 3339 timestamp decodes too, as do a TOML offset datetime and a
YAML timestamp. Z is datetime.UTC, and a numeric offset is a
timezone fixed at that offset, written back as
2026-10-06T21:00:00-04:00[-04:00]. Decoding fails on a timestamp with no
offset, an unknown zone name, or an offset the zone does not have at that
instant. A zone with no IANA name is written as its offset, and to_raw
raises ValueError for a naive datetime. Two datetimes compare by
instant, as Python’s always do, so a map holds one key per instant whatever
its zone.
The zone names come from ZoneInfo, which reads the
system’s zone files. A program that may run without them, as on Windows,
installs the tzdata package, which
ZoneInfo falls back to.
Time windows#
A time field that declares a window also emits it as a class constant on
the struct:
start_time_window: ClassVar[tuple[time, time]] = (time(9, 0), time(21, 0))
It is metadata for a user interface, not a constraint. Nothing in validate
consults it.
Routes#
Python generates nothing for a route type. Routes reach Go and
TypeScript only. A model that mixes routes with other types still generates
its structs, enums, and unions into the Python module as usual.