GitHub

Pydantic and msgspec

Use pydantic models and msgspec structs as pyfect schemas, and pyfect schemas in pydantic.

The pydantic and msgspec extras (pyfect-dev[pydantic], pyfect-dev[msgspec]) let you keep the models you have and still decode with schemas.

pyfect.pydantic.from_model(Model) is a schema of a pydantic model: it decodes JSON values with Model.model_validate and encodes with model_dump(mode="json"), and each pydantic error becomes an issue at its path, so errors="all" reports every problem at once. pyfect.msgspec.from_struct(Struct) does the same for a msgspec struct with msgspec.convert and msgspec.to_builtins (msgspec stops at the first error). Both compose like any schema: in S.Array, or under S.from_json_string, which is also how they become a config value (config.schema(S.from_json_string(from_model(Db)), "DB")): a bare one is refused, as Effect's Config.schema refuses Schema.Json.

Going the other way, a pyfect schema is a pydantic field type: annotate a field with it, and pydantic decodes, encodes and writes the JSON Schema with it.

models.py
from typing import Annotated

import msgspec
from pydantic import BaseModel

import pyfect as fx
from pyfect import msgspec as fx_msgspec
from pyfect import pydantic as fx_pydantic
from pyfect import schema as S


# A pydantic model as a pyfect schema: decoded with `model_validate`, encoded
# with `model_dump(mode="json")`, pydantic's errors as issues at their paths.
class Job(BaseModel):
    name: str
    schedule: str


class HarvestFile(BaseModel):
    timezone: str
    jobs: list[Job]


config = S.from_json_string(fx_pydantic.from_model(HarvestFile))
text = '{"timezone": "UTC", "jobs": [{"name": "countries", "schedule": "*/5 * * * *"}]}'
print(S.decode_unknown_sync(config)(text))
bad = S.decode_unknown_result(config)('{"jobs": [{"schedule": 5}]}', errors="all")
assert isinstance(bad, fx.Err)
print(bad.error.message)


# A msgspec struct as a pyfect schema, composed like any other.
class Change(msgspec.Struct):
    key: str
    op: str


log = S.from_json_string(S.Array(fx_msgspec.from_struct(Change)))
changes = S.decode_unknown_sync(log)('[{"key": "fr", "op": "add"}]')
assert changes == (Change(key="fr", op="add"),)
print(S.encode_sync(log)(changes))


# The other way: a pyfect schema as a pydantic field type.
class Order(BaseModel):
    total: Annotated[float, S.FiniteFromString]


print(Order.model_validate({"total": "9.5"}).total)

Reference: pyfect.pydantic, pyfect.msgspec.