GitHub

API reference for msgspec.

msgspec structs as pyfect schemas. Needs the msgspec extra (pyfect-dev[msgspec]).

from_struct(Item) is a pyfect schema of the struct: it decodes JSON values with msgspec.convert and encodes with msgspec.to_builtins, so it composes with the rest of a schema (S.Array(from_struct(Item)), S.to_codec_json, config.schema) and fails with a pyfect issue at the path msgspec reports (msgspec stops at the first error)::

import msgspec

from pyfect import msgspec as M
from pyfect import schema as S

class Item(msgspec.Struct):
    sku: str
    qty: int

items = S.decode_unknown_sync(S.Array(M.from_struct(Item)))([{"sku": "a", "qty": 1}])

Functions

from_struct

from_struct[S: msgspec.Struct](struct, /, *, strict=True) -> Bottom[S, JsonValue]

struct as a pyfect schema: decodes a JSON value with msgspec.convert(value, struct, strict=strict) (strict=False also reads numbers and booleans from strings), encodes with msgspec.to_builtins.

ParameterTypeDescription
structtype[S]
strictbool = True

Returns Bottom[S, JsonValue]

def from_struct[S: msgspec.Struct](
    struct: type[S], /, *, strict: bool = True
) -> Bottom[S, JsonValue]:
    """``struct`` as a pyfect schema: decodes a JSON value with
    ``msgspec.convert(value, struct, strict=strict)`` (``strict=False``
    also reads numbers and booleans from strings), encodes with
    ``msgspec.to_builtins``."""

    def decode(input: JsonValue, _options: ParseOptions) -> Exit[S, Issue]:
        try:
            return Success(msgspec.convert(input, struct, strict=strict))
        except msgspec.ValidationError as error:
            return fail_exit(_issue_of(error))

    def encode(value: S, _options: ParseOptions) -> Exit[JsonValue, Issue]:
        return Success(cast("JsonValue", msgspec.to_builtins(value)))

    target = instance_of(struct)
    return Json.pipe(decode_to(target, T.transform_effect(decode=decode, encode=encode)))