GitHub

representation

API reference for representation.

Schema representations (Effect's SchemaRepresentation): a schema's encoded side as plain, comparable, persistable data.

to_representation(schema) lowers a schema to a Document (one Representation and the named references it uses); to_json / from_json persist it in Effect's JSON form; from_representation rebuilds a schema from it, given the revivers of the declarations and checks it holds (BUILTIN_REVIVERS for pyfect's own); to_json_schema_document compiles it to JSON Schema.

from pyfect.schema import representation as R

stored = R.to_json(R.to_representation(Person))
schema = R.from_representation(R.from_json(stored), revivers=R.BUILTIN_REVIVERS)

Re-exports

Values

AttributeTypeDescription
BUILTIN_REVIVERStuple[AnyReviver, ...]

Every built-in reviver.

big_decimal_reviverDeclarationReviver[None]
byte_size_reviverDeclarationReviver[None]
bytes_reviverDeclarationReviver[None]

Effect's Uint8ArrayReviver: revives S.Bytes.

cause_reason_reviverDeclarationReviver[None]
cause_reviverDeclarationReviver[None]
date_time_utc_reviverDeclarationReviver[None]
date_time_zoned_reviverDeclarationReviver[None]
duration_reviverDeclarationReviver[None]
error_instance_reviverDeclarationReviver[Mapping[str, Any] | None]
exit_reviverDeclarationReviver[None]
frozen_set_reviverDeclarationReviver[None]

Effect's ReadonlySetReviver: revives S.FrozenSet.

graph_reviverDeclarationReviver[Literal['directed', 'undirected']]

Effect's GraphReviver: revives S.Graph, its kind the payload.

hash_map_reviverDeclarationReviver[None]

Effect's HashMapReviver: revives S.HashMap.

hash_set_reviverDeclarationReviver[None]

Effect's HashSetReviver: revives S.HashSet.

is_ascii_reviverFilterReviver[None]
is_base64_reviverFilterReviver[None]
is_base64_url_reviverFilterReviver[None]
is_between_big_int_reviverFilterReviver[Mapping[str, Any]]
is_between_code_points_reviverFilterReviver[Mapping[str, Any]]
is_between_date_reviverFilterReviver[Mapping[str, Any]]
is_between_length_reviverFilterReviver[Mapping[str, Any]]
is_between_properties_reviverFilterReviver[Mapping[str, Any]]
is_between_reviverFilterReviver[Mapping[str, Any]]
is_between_size_reviverFilterReviver[Mapping[str, Any]]
is_capitalized_reviverFilterReviver[None]
is_ending_with_reviverFilterReviver[Mapping[str, Any]]
is_finite_reviverFilterReviver[None]
is_greater_than_big_int_reviverFilterReviver[Mapping[str, Any]]
is_greater_than_date_reviverFilterReviver[Mapping[str, Any]]
is_greater_than_or_equal_to_big_int_reviverFilterReviver[Mapping[str, Any]]
is_greater_than_or_equal_to_date_reviverFilterReviver[Mapping[str, Any]]
is_greater_than_or_equal_to_reviverFilterReviver[Mapping[str, Any]]
is_greater_than_reviverFilterReviver[Mapping[str, Any]]
is_guid_reviverFilterReviver[None]
is_including_reviverFilterReviver[Mapping[str, Any]]
is_int_reviverFilterReviver[None]
is_less_than_big_int_reviverFilterReviver[Mapping[str, Any]]
is_less_than_date_reviverFilterReviver[Mapping[str, Any]]
is_less_than_or_equal_to_big_int_reviverFilterReviver[Mapping[str, Any]]
is_less_than_or_equal_to_date_reviverFilterReviver[Mapping[str, Any]]
is_less_than_or_equal_to_reviverFilterReviver[Mapping[str, Any]]
is_less_than_reviverFilterReviver[Mapping[str, Any]]
is_lowercased_reviverFilterReviver[None]
is_max_code_points_reviverFilterReviver[Mapping[str, Any]]
is_max_length_reviverFilterReviver[Mapping[str, Any]]
is_max_properties_reviverFilterReviver[Mapping[str, Any]]
is_max_size_reviverFilterReviver[Mapping[str, Any]]
is_min_code_points_reviverFilterReviver[Mapping[str, Any]]
is_min_length_reviverFilterReviver[Mapping[str, Any]]
is_min_properties_reviverFilterReviver[Mapping[str, Any]]
is_min_size_reviverFilterReviver[Mapping[str, Any]]
is_multiple_of_reviverFilterReviver[Mapping[str, Any]]
is_pattern_reviverFilterReviver[Mapping[str, Any]]
is_property_names_reviverFilterReviver[None]
is_starting_with_reviverFilterReviver[Mapping[str, Any]]
is_string_big_int_reviverFilterReviver[None]
is_string_finite_reviverFilterReviver[None]
is_trimmed_reviverFilterReviver[None]
is_ulid_reviverFilterReviver[None]
is_uncapitalized_reviverFilterReviver[None]
is_unique_key_reviverFilterReviver[None]
is_unique_reviverFilterReviver[None]
is_uppercased_reviverFilterReviver[None]
is_uuid_reviverFilterReviver[Mapping[str, Any]]
json_reviverDeclarationReviver[None]
map_reviverDeclarationReviver[None]

Effect's ReadonlyMapReviver: revives S.Map.

mutable_json_reviverDeclarationReviver[None]

Effect's MutableJsonReviver: Python's JSON values are mutable already, so it revives S.Json.

option_reviverDeclarationReviver[None]
redacted_reviverDeclarationReviver[Mapping[str, Any] | None]
reg_exp_reviverDeclarationReviver[None]
result_reviverDeclarationReviver[None]
sem_ver_range_reviverDeclarationReviver[None]
sem_ver_reviverDeclarationReviver[None]
time_zone_named_reviverDeclarationReviver[None]
time_zone_offset_reviverDeclarationReviver[None]
time_zone_reviverDeclarationReviver[None]
url_reviverDeclarationReviver[None]

Types

TypeDefinitionDescription
Artifacttype Artifact = ImportArtifact | TypedDictArtifact | EnumArtifact
ImportedSchematype ImportedSchema = Bottom[object, object, Never, Never]

A schema read from JSON Schema: nothing is known of its values statically, and it needs no services.

PatternModetype PatternMode = TypingLiteral['error', 'ignore', 'apply']
Annotationstype Annotations = Mapping[str, object]
Checktype Check = Filter | FilterGroup
EnumValuetype EnumValue = str | int | float
Jsontype Json = bool | int | float | str | list[Json] | dict[str, Json] | None
LiteralValuetype LiteralValue = str | int | float | bool
PropertyNametype PropertyName = str | int | float
Referencestype References = Mapping[str, Representation]
Representationtype Representation = Declaration | Reference | Suspend | Null | Undefined | Void | ObjectKeyword | Never | Unknown | Any | String | Number | Boolean | BigInt | Literal | Enum | TemplateLiteral | Arrays | Objects | Union
AnyRevivertype AnyReviver = DeclarationReviver[Any] | FilterReviver[Any] | FilterGroupReviver[Any]
AnySchematype AnySchema = Bottom[object, object, object, object]

A revived schema: its node is known, its types are not (Effect's Schema.Top).

Classes

Functions

make_code

make_code(runtime, type) -> Code

Code(runtime, type) (Effect's makeCode).

ParameterTypeDescription
runtimestr
typestr

Returns Code

def make_code(runtime: str, type: str, /) -> Code:
    """``Code(runtime, type)`` (Effect's ``makeCode``)."""
    return Code(runtime, type)

to_code_document

to_code_document(document) -> CodeDocument

Python source for document's schemas: an expression and a type for each root and each reference, and the artifacts they use. A check or declaration pyfect does not know gives its source through a to_code annotation (GeneratedCheck / GeneratedDeclaration); without one this raises RepresentationError. S.Int is written S.Number.check(S.is_int()), which it is in a document: it then accepts 1.0 too.

ParameterTypeDescription
documentR.MultiDocument

Returns CodeDocument

def to_code_document(document: R.MultiDocument, /) -> CodeDocument:
    """Python source for ``document``'s schemas: an expression and a type for each
    root and each reference, and the artifacts they use. A check or declaration
    pyfect does not know gives its source through a ``to_code`` annotation
    (``GeneratedCheck`` / ``GeneratedDeclaration``); without one this raises
    ``RepresentationError``. ``S.Int`` is written ``S.Number.check(S.is_int())``,
    which it is in a document: it then accepts ``1.0`` too."""
    generator = _Generator(document)
    sorted = generator.sorted
    for ref, _ in sorted.non_recursives:
        generator.identifier(ref)
    for ref in sorted.recursives:
        generator.identifier(ref)
    non_recursives = tuple(
        NamedCode(generator.identifier(ref), generator.recur(node, ("references", ref)))
        for ref, node in sorted.non_recursives
    )
    recursives: dict[str, Code] = {}
    for ref, node in sorted.recursives.items():
        generator.compiling_recursive = True
        recursives[generator.identifier(ref)] = generator.recur(node, ("references", ref))
        generator.compiling_recursive = False
    first, *rest = (
        generator.recur(node, ("representations", i))
        for i, node in enumerate(document.representations)
    )
    return CodeDocument(
        (first, *rest),
        CodeReferences(non_recursives, recursives),
        tuple(generator.artifacts),
    )

to_code_module

to_code_module(document, /, *, names=()) -> str

document as one module: imports, type aliases (they may refer to each other), artifacts, references in order, then a variable for each root, named by names (Schema0, ... by default). Run it, or check it with pyright.

ParameterTypeDescription
documentCodeDocument
namesSequence[str] = ()

Returns str

def to_code_module(document: CodeDocument, /, *, names: Sequence[str] = ()) -> str:
    """``document`` as one module: imports, type aliases (they may refer to each
    other), artifacts, references in order, then a variable for each root, named by
    ``names`` (``Schema0``, ... by default). Run it, or check it with pyright."""
    _check_root_names(names, document)
    root_names = [names[i] if i < len(names) else f"Schema{i}" for i in range(len(document.codes))]
    recursives = document.references.recursives
    non_recursives = document.references.non_recursives
    lines = [f"type {named.identifier}Type = {named.code.type}" for named in non_recursives]
    lines += [f"type {identifier}Type = {code.type}" for identifier, code in recursives.items()]
    lines += [
        f"type {name}Type = {code.type}"
        for name, code in zip(root_names, document.codes, strict=True)
    ]
    lines += [
        artifact.code.runtime
        for artifact in document.artifacts
        if isinstance(artifact, (TypedDictArtifact, EnumArtifact))
    ]
    definitions = {
        named.identifier: (f"{named.identifier} = {named.code.runtime}", named.code.runtime)
        for named in non_recursives
    }
    for identifier, code in recursives.items():
        annotated = f"{identifier}: S.Bottom[{identifier}Type, Any, Any, Any] = {code.runtime}"
        definitions[identifier] = (annotated, code.runtime)
    lines += _in_definition_order(definitions)
    lines += [
        f"{name} = {code.runtime}" for name, code in zip(root_names, document.codes, strict=True)
    ]
    body = "\n".join(lines) + "\n"
    header = [
        "from __future__ import annotations",
        "",
        *_imports(document.artifacts, body),
        "",
        "from pyfect import schema as S",
        "",
    ]
    return "\n".join(header) + "\n" + body

from_representation

from_representation(document, /, *, revivers) -> AnySchema

The schema document describes.

ParameterTypeDescription
documentR.Document
reviversSequence[AnyReviver]

Returns AnySchema

def from_representation(document: R.Document, /, *, revivers: Sequence[AnyReviver]) -> AnySchema:
    """The schema ``document`` describes."""
    return Reviving(document.references, revivers).root(
        document.representation, ("representation",)
    )

from_representations

from_representations(document, /, *, revivers) -> tuple[AnySchema, *(tuple[AnySchema, ...])]

The schemas of document's roots, sharing their references; only references reachable from a root are revived.

ParameterTypeDescription
documentR.MultiDocument
reviversSequence[AnyReviver]

Returns tuple[AnySchema, *(tuple[AnySchema, ...])]

def from_representations(
    document: R.MultiDocument, /, *, revivers: Sequence[AnyReviver]
) -> tuple[AnySchema, *tuple[AnySchema, ...]]:
    """The schemas of ``document``'s roots, sharing their references; only
    references reachable from a root are revived."""
    reviving = Reviving(document.references, revivers)
    first, *rest = (
        reviving.root(r, ("representations", i)) for i, r in enumerate(document.representations)
    )
    return (first, *rest)

from_json_schema_document

from_json_schema_document(document, /, *, on_enter=None, patterns='error', include_annotation_key=None, close_objects=False) -> ImportedSchema

The schema document describes. on_enter replaces each schema object before it is read; patterns says what a pattern or patternProperties does: "error" rejects it, "ignore" skips it, "apply" enforces it (for trusted documents only, as a regular expression may run for an unbounded time). include_annotation_key selects other keys to keep as annotations.

close_objects (experimental) closes an object with declared properties when every object schema it combines omits additionalProperties, after allOf is merged, so inherited properties stay valid. Decoding then strips other keys, or rejects them with on_excess_property="error".

ParameterTypeDescription
documentDocument[Draft2020]
on_enterCallable[[JsonSchema], JsonSchema] | None = None
patternsPatternMode = 'error'
include_annotation_keyCallable[[str], bool] | None = None
close_objectsbool = False

Returns ImportedSchema

def from_json_schema_document(
    document: Document[Draft2020],
    /,
    *,
    on_enter: Callable[[JsonSchema], JsonSchema] | None = None,
    patterns: PatternMode = "error",
    include_annotation_key: Callable[[str], bool] | None = None,
    close_objects: bool = False,
) -> ImportedSchema:
    """The schema ``document`` describes. ``on_enter`` replaces each schema
    object before it is read; ``patterns`` says what a ``pattern`` or
    ``patternProperties`` does: ``"error"`` rejects it, ``"ignore"`` skips it,
    ``"apply"`` enforces it (for trusted documents only, as a regular
    expression may run for an unbounded time). ``include_annotation_key``
    selects other keys to keep as annotations.

    ``close_objects`` (experimental) closes an object with declared properties
    when every object schema it combines omits ``additionalProperties``, after
    ``allOf`` is merged, so inherited properties stay valid. Decoding then
    strips other keys, or rejects them with ``on_excess_property="error"``."""
    options = Options(on_enter, patterns, include_annotation_key, close_objects)
    schema, definitions = js_ordered((document.schema, document.definitions))
    return _import((schema,), definitions, lambda _: ("schema",), options)[0]

from_json_schema_multi_document

from_json_schema_multi_document(document, /, *, on_enter=None, patterns='error', include_annotation_key=None, close_objects=False) -> tuple[ImportedSchema, *(tuple[ImportedSchema, ...])]

The schemas of document's roots, sharing their definitions; only definitions a root reaches are read. Options as from_json_schema_document.

ParameterTypeDescription
documentMultiDocument[Draft2020]
on_enterCallable[[JsonSchema], JsonSchema] | None = None
patternsPatternMode = 'error'
include_annotation_keyCallable[[str], bool] | None = None
close_objectsbool = False

Returns tuple[ImportedSchema, *(tuple[ImportedSchema, ...])]

def from_json_schema_multi_document(
    document: MultiDocument[Draft2020],
    /,
    *,
    on_enter: Callable[[JsonSchema], JsonSchema] | None = None,
    patterns: PatternMode = "error",
    include_annotation_key: Callable[[str], bool] | None = None,
    close_objects: bool = False,
) -> tuple[ImportedSchema, *tuple[ImportedSchema, ...]]:
    """The schemas of ``document``'s roots, sharing their definitions; only
    definitions a root reaches are read. Options as
    ``from_json_schema_document``."""
    options = Options(on_enter, patterns, include_annotation_key, close_objects)
    schemas, definitions = js_ordered((document.schemas, document.definitions))
    out = _import(schemas, definitions, lambda i: ("schemas", i), options)
    return cast("tuple[ImportedSchema, *tuple[ImportedSchema, ...]]", out)

from_json

from_json(input) -> R.Document

The document input (to_json's output) holds.

ParameterTypeDescription
inputobject

Returns R.Document

def from_json(input: object, /) -> R.Document:
    """The document ``input`` (``to_json``'s output) holds."""
    document = _object(input, ())
    return R.Document(
        _decode(_key(document, "representation", ()), ("representation",)),
        _decode_references(document),
    )

from_json_multi_document

from_json_multi_document(input) -> R.MultiDocument

The multi-document input (to_json_multi_document's output) holds.

ParameterTypeDescription
inputobject

Returns R.MultiDocument

def from_json_multi_document(input: object, /) -> R.MultiDocument:
    """The multi-document ``input`` (``to_json_multi_document``'s output) holds."""
    document = _object(input, ())
    roots = _array(_key(document, "representations", ()), ("representations",))
    if not roots:
        raise error_with_path("Missing key", ("representations", 0))
    first, *rest = (_decode(r, ("representations", i)) for i, r in enumerate(roots))
    return R.MultiDocument((first, *rest), _decode_references(document))

to_json

to_json(document) -> Json

document as JSON.

ParameterTypeDescription
documentR.Document

Returns Json

def to_json(document: R.Document, /) -> Json:
    """``document`` as JSON."""
    path: Path = ("representation",)
    return {
        "representation": _encode(document.representation, path),
        "references": _encode_references(document.references),
    }

to_json_multi_document

to_json_multi_document(document) -> Json

document as JSON, its roots in order.

ParameterTypeDescription
documentR.MultiDocument

Returns Json

def to_json_multi_document(document: R.MultiDocument, /) -> Json:
    """``document`` as JSON, its roots in order."""
    return {
        "representations": [
            _encode(r, ("representations", i)) for i, r in enumerate(document.representations)
        ],
        "references": _encode_references(document.references),
    }

to_json_schema_document

to_json_schema_document(document, /, *, on_excess_property='ignore', generate_descriptions=False, include_annotation_key=None) -> Document[Draft2020]

The JSON Schema of document's representation, its references the definitions.

ParameterTypeDescription
documentR.Document
on_excess_propertyOnExcessProperty = 'ignore'
generate_descriptionsbool = False
include_annotation_keyCallable[[str], bool] | None = None

Returns Document[Draft2020]

def to_json_schema_document(
    document: R.Document,
    /,
    *,
    on_excess_property: OnExcessProperty = "ignore",
    generate_descriptions: bool = False,
    include_annotation_key: Callable[[str], bool] | None = None,
) -> Document[Draft2020]:
    """The JSON Schema of ``document``'s representation, its references
    the definitions."""
    multi = _compile(
        R.to_multi_document(document),
        [("representation",)],
        Options(on_excess_property, generate_descriptions, include_annotation_key),
    )
    return Document("draft-2020-12", multi.schemas[0], multi.definitions)

to_json_schema_multi_document

to_json_schema_multi_document(document, /, *, on_excess_property='ignore', generate_descriptions=False, include_annotation_key=None) -> MultiDocument[Draft2020]

The JSON Schemas of document's roots, its references their definitions (every one is compiled, reachable or not). The options are S.to_json_schema_multi_document's; references are already decided.

ParameterTypeDescription
documentR.MultiDocument
on_excess_propertyOnExcessProperty = 'ignore'
generate_descriptionsbool = False
include_annotation_keyCallable[[str], bool] | None = None

Returns MultiDocument[Draft2020]

def to_json_schema_multi_document(
    document: R.MultiDocument,
    /,
    *,
    on_excess_property: OnExcessProperty = "ignore",
    generate_descriptions: bool = False,
    include_annotation_key: Callable[[str], bool] | None = None,
) -> MultiDocument[Draft2020]:
    """The JSON Schemas of ``document``'s roots, its references their
    definitions (every one is compiled, reachable or not). The options are
    ``S.to_json_schema_multi_document``'s; references are already decided."""
    paths = [("representations", i) for i in range(len(document.representations))]
    return _compile(
        document, paths, Options(on_excess_property, generate_descriptions, include_annotation_key)
    )

to_multi_document

to_multi_document(document) -> MultiDocument

document as a multi-document of one root (Effect's toMultiDocument).

ParameterTypeDescription
documentDocument

Returns MultiDocument

def to_multi_document(document: Document) -> MultiDocument:
    """``document`` as a multi-document of one root (Effect's
    ``toMultiDocument``)."""
    return MultiDocument((document.representation,), document.references)

make_reviver_declaration

make_reviver_declaration[P](id, payload_schema, revive) -> DeclarationReviver[P]

A declaration reviver, its payload type read from payload_schema.

ParameterTypeDescription
idstr
payload_schemaPayloadSchema[P]
reviveCallable[[DeclarationInput[P]], Top]

Returns DeclarationReviver[P]

def make_reviver_declaration[P](
    id: str, payload_schema: PayloadSchema[P], revive: Callable[[DeclarationInput[P]], Top], /
) -> DeclarationReviver[P]:
    """A declaration reviver, its payload type read from ``payload_schema``."""
    return DeclarationReviver(id, payload_schema, revive)

make_reviver_filter

make_reviver_filter[P](id, payload_schema, revive) -> FilterReviver[P]

A filter reviver, its payload type read from payload_schema.

ParameterTypeDescription
idstr
payload_schemaPayloadSchema[P]
reviveCallable[[CheckInput[P]], Filter[Any]]

Returns FilterReviver[P]

def make_reviver_filter[P](
    id: str, payload_schema: PayloadSchema[P], revive: Callable[[CheckInput[P]], Filter[Any]], /
) -> FilterReviver[P]:
    """A filter reviver, its payload type read from ``payload_schema``."""
    return FilterReviver(id, payload_schema, revive)

make_reviver_filter_group

make_reviver_filter_group[P](id, payload_schema, revive) -> FilterGroupReviver[P]

A filter group reviver, its payload type read from payload_schema.

ParameterTypeDescription
idstr
payload_schemaPayloadSchema[P]
reviveCallable[[CheckInput[P]], FilterGroup[Any]]

Returns FilterGroupReviver[P]

def make_reviver_filter_group[P](
    id: str,
    payload_schema: PayloadSchema[P],
    revive: Callable[[CheckInput[P]], FilterGroup[Any]],
    /,
) -> FilterGroupReviver[P]:
    """A filter group reviver, its payload type read from ``payload_schema``."""
    return FilterGroupReviver(id, payload_schema, revive)

to_representation

to_representation(schema, /, *, reference_policy=None) -> R.Document

The document of schema's encoded side. reference_policy names the nodes that become references (default: their identifier); a recursive node is one whatever it says.

ParameterTypeDescription
schemaTop
reference_policyReferencePolicy | None = None

Returns R.Document

def to_representation(
    schema: Top, /, *, reference_policy: ReferencePolicy | None = None
) -> R.Document:
    """The document of ``schema``'s encoded side. ``reference_policy``
    names the nodes that become references (default: their
    ``identifier``); a recursive node is one whatever it says."""
    multi = to_representations((schema,), reference_policy=reference_policy)
    return R.Document(multi.representations[0], multi.references)

to_representations

to_representations(schemas, /, *, reference_policy=None) -> R.MultiDocument

The documents of several schemas, sharing their references.

ParameterTypeDescription
schemastuple[Top, *(tuple[Top, ...])]
reference_policyReferencePolicy | None = None

Returns R.MultiDocument

def to_representations(
    schemas: tuple[Top, *tuple[Top, ...]], /, *, reference_policy: ReferencePolicy | None = None
) -> R.MultiDocument:
    """The documents of several schemas, sharing their references."""
    roots = [schema.__codec__().ast for schema in schemas]
    lowering = _Lowering(References(roots, reference_policy))
    first, *rest = (lowering.recur(root) for root in roots)
    return R.MultiDocument((first, *rest), lowering.references)