GitHub

pydantic

API reference for pydantic.

Pydantic and pyfect schemas, each usable in the other. Needs the pydantic extra (pyfect-dev[pydantic]).

A pyfect schema is a pydantic field type: annotate the field with it::

from typing import Annotated

from pydantic import BaseModel

from pyfect import schema as S

class Order(BaseModel):
    total: Annotated[float, S.FiniteFromString]

Python input the schema's decoded side accepts is kept as it is (so pydantic's revalidation and validate_assignment never decode twice); other Python input is decoded with the schema, JSON input with S.to_codec_json(schema); dumping encodes the same way, and the JSON Schema is the schema's. A schema class (S.Class) works as a field type directly. A failure is one pydantic error, the pyfect message. Only schemas that need no services can run inside pydantic.

from_model(Model) goes the other way: a pyfect schema of a pydantic model, decoding JSON values with Model.model_validate and encoding with model_dump(mode="json"); pydantic's errors become a pyfect issue tree.

Functions

core_schema_of

core_schema_of(schema) -> CoreSchema

The pydantic core schema validating and serializing with schema (what __get_pydantic_core_schema__ of a pyfect schema returns).

ParameterTypeDescription
schema_Codec

Returns CoreSchema

def core_schema_of(schema: _Codec, /) -> CoreSchema:
    """The pydantic core schema validating and serializing with ``schema``
    (what ``__get_pydantic_core_schema__`` of a pyfect schema returns)."""
    json_codec = to_codec_json(schema)
    decoded_side = schema.__codec__().ast.to_type()

    def decode_python(input: object) -> object:
        # A decoded value is kept first, so validating again (pydantic's
        # revalidation and assignment) never decodes a value twice.
        match schema_ast.run_now(decoded_side.parse(input, {})):
            case Success(value):
                return value
            case Failure():
                return _unwrap(decode_unknown_result(schema)(input))

    def decode_json(input: object) -> object:
        return _unwrap(decode_unknown_result(json_codec)(input))

    def serialize(value: object, info: core_schema.SerializationInfo) -> object:
        codec = json_codec if info.mode_is_json() else schema
        return _unwrap(encode_unknown_result(codec)(value))

    return core_schema.json_or_python_schema(
        json_schema=core_schema.no_info_plain_validator_function(decode_json),
        python_schema=core_schema.no_info_plain_validator_function(decode_python),
        serialization=core_schema.plain_serializer_function_ser_schema(serialize, info_arg=True),
    )

json_schema_of

json_schema_of(schema) -> dict[str, Any]

schema's JSON Schema for pydantic, with its definitions inlined (pydantic keeps its own $defs); a recursive reference is left unconstrained.

ParameterTypeDescription
schema_Codec

Returns dict[str, Any]

def json_schema_of(schema: _Codec, /) -> dict[str, Any]:
    """``schema``'s JSON Schema for pydantic, with its definitions inlined
    (pydantic keeps its own ``$defs``); a recursive reference is left
    unconstrained."""
    document = to_json_schema_document(schema)
    return cast("dict[str, Any]", _inline(document.schema, document.definitions, ()))

get_pydantic_core_schema

get_pydantic_core_schema(schema, _source, _handler) -> CoreSchema
ParameterTypeDescription
schema_Codec
_sourceobject
_handlerGetCoreSchemaHandler

Returns CoreSchema

def get_pydantic_core_schema(
    schema: _Codec, _source: object, _handler: GetCoreSchemaHandler
) -> CoreSchema:
    return core_schema_of(schema)

get_pydantic_json_schema

get_pydantic_json_schema(schema, _core, _handler) -> dict[str, Any]
ParameterTypeDescription
schema_Codec
_coreCoreSchema
_handlerGetJsonSchemaHandler

Returns dict[str, Any]

def get_pydantic_json_schema(
    schema: _Codec, _core: CoreSchema, _handler: GetJsonSchemaHandler
) -> dict[str, Any]:
    return json_schema_of(schema)

from_model

from_model[M: BaseModel](model) -> Bottom[M, JsonValue]

model as a pyfect schema: decodes a JSON value with model.model_validate, encodes with model_dump(mode="json"). Each pydantic error is an issue at its location (Missing key for a missing field); only the first unless decoding with errors="all".

ParameterTypeDescription
modeltype[M]

Returns Bottom[M, JsonValue]

def from_model[M: BaseModel](model: type[M], /) -> Bottom[M, JsonValue]:
    """``model`` as a pyfect schema: decodes a JSON value with
    ``model.model_validate``, encodes with ``model_dump(mode="json")``.
    Each pydantic error is an issue at its location (``Missing key`` for a
    missing field); only the first unless decoding with ``errors="all"``."""
    target = instance_of(model)
    node = target.ast

    def decode(input: JsonValue, options: ParseOptions) -> Exit[M, Issue]:
        try:
            return Success(model.model_validate(input))
        except ValidationError as error:
            return fail_exit(_issue_of(error, node, every=options.get("errors") == "all"))

    def encode(value: M, _options: ParseOptions) -> Exit[JsonValue, Issue]:
        return Success(cast("JsonValue", value.model_dump(mode="json")))

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