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#
| Attribute | Type | Description |
|---|---|---|
BUILTIN_REVIVERS | tuple[AnyReviver, ...] | Every built-in reviver. |
big_decimal_reviver | DeclarationReviver[None] | |
byte_size_reviver | DeclarationReviver[None] | |
bytes_reviver | DeclarationReviver[None] | Effect's |
cause_reason_reviver | DeclarationReviver[None] | |
cause_reviver | DeclarationReviver[None] | |
date_time_utc_reviver | DeclarationReviver[None] | |
date_time_zoned_reviver | DeclarationReviver[None] | |
duration_reviver | DeclarationReviver[None] | |
error_instance_reviver | DeclarationReviver[Mapping[str, Any] | None] | |
exit_reviver | DeclarationReviver[None] | |
frozen_set_reviver | DeclarationReviver[None] | Effect's |
graph_reviver | DeclarationReviver[Literal['directed', 'undirected']] | Effect's |
hash_map_reviver | DeclarationReviver[None] | Effect's |
hash_set_reviver | DeclarationReviver[None] | Effect's |
is_ascii_reviver | FilterReviver[None] | |
is_base64_reviver | FilterReviver[None] | |
is_base64_url_reviver | FilterReviver[None] | |
is_between_big_int_reviver | FilterReviver[Mapping[str, Any]] | |
is_between_code_points_reviver | FilterReviver[Mapping[str, Any]] | |
is_between_date_reviver | FilterReviver[Mapping[str, Any]] | |
is_between_length_reviver | FilterReviver[Mapping[str, Any]] | |
is_between_properties_reviver | FilterReviver[Mapping[str, Any]] | |
is_between_reviver | FilterReviver[Mapping[str, Any]] | |
is_between_size_reviver | FilterReviver[Mapping[str, Any]] | |
is_capitalized_reviver | FilterReviver[None] | |
is_ending_with_reviver | FilterReviver[Mapping[str, Any]] | |
is_finite_reviver | FilterReviver[None] | |
is_greater_than_big_int_reviver | FilterReviver[Mapping[str, Any]] | |
is_greater_than_date_reviver | FilterReviver[Mapping[str, Any]] | |
is_greater_than_or_equal_to_big_int_reviver | FilterReviver[Mapping[str, Any]] | |
is_greater_than_or_equal_to_date_reviver | FilterReviver[Mapping[str, Any]] | |
is_greater_than_or_equal_to_reviver | FilterReviver[Mapping[str, Any]] | |
is_greater_than_reviver | FilterReviver[Mapping[str, Any]] | |
is_guid_reviver | FilterReviver[None] | |
is_including_reviver | FilterReviver[Mapping[str, Any]] | |
is_int_reviver | FilterReviver[None] | |
is_less_than_big_int_reviver | FilterReviver[Mapping[str, Any]] | |
is_less_than_date_reviver | FilterReviver[Mapping[str, Any]] | |
is_less_than_or_equal_to_big_int_reviver | FilterReviver[Mapping[str, Any]] | |
is_less_than_or_equal_to_date_reviver | FilterReviver[Mapping[str, Any]] | |
is_less_than_or_equal_to_reviver | FilterReviver[Mapping[str, Any]] | |
is_less_than_reviver | FilterReviver[Mapping[str, Any]] | |
is_lowercased_reviver | FilterReviver[None] | |
is_max_code_points_reviver | FilterReviver[Mapping[str, Any]] | |
is_max_length_reviver | FilterReviver[Mapping[str, Any]] | |
is_max_properties_reviver | FilterReviver[Mapping[str, Any]] | |
is_max_size_reviver | FilterReviver[Mapping[str, Any]] | |
is_min_code_points_reviver | FilterReviver[Mapping[str, Any]] | |
is_min_length_reviver | FilterReviver[Mapping[str, Any]] | |
is_min_properties_reviver | FilterReviver[Mapping[str, Any]] | |
is_min_size_reviver | FilterReviver[Mapping[str, Any]] | |
is_multiple_of_reviver | FilterReviver[Mapping[str, Any]] | |
is_pattern_reviver | FilterReviver[Mapping[str, Any]] | |
is_property_names_reviver | FilterReviver[None] | |
is_starting_with_reviver | FilterReviver[Mapping[str, Any]] | |
is_string_big_int_reviver | FilterReviver[None] | |
is_string_finite_reviver | FilterReviver[None] | |
is_trimmed_reviver | FilterReviver[None] | |
is_ulid_reviver | FilterReviver[None] | |
is_uncapitalized_reviver | FilterReviver[None] | |
is_unique_key_reviver | FilterReviver[None] | |
is_unique_reviver | FilterReviver[None] | |
is_uppercased_reviver | FilterReviver[None] | |
is_uuid_reviver | FilterReviver[Mapping[str, Any]] | |
json_reviver | DeclarationReviver[None] | |
map_reviver | DeclarationReviver[None] | Effect's |
mutable_json_reviver | DeclarationReviver[None] | Effect's |
option_reviver | DeclarationReviver[None] | |
redacted_reviver | DeclarationReviver[Mapping[str, Any] | None] | |
reg_exp_reviver | DeclarationReviver[None] | |
result_reviver | DeclarationReviver[None] | |
sem_ver_range_reviver | DeclarationReviver[None] | |
sem_ver_reviver | DeclarationReviver[None] | |
time_zone_named_reviver | DeclarationReviver[None] | |
time_zone_offset_reviver | DeclarationReviver[None] | |
time_zone_reviver | DeclarationReviver[None] | |
url_reviver | DeclarationReviver[None] |
Types#
| Type | Definition | Description |
|---|---|---|
Artifact | type Artifact = ImportArtifact | TypedDictArtifact | EnumArtifact | |
ImportedSchema | type ImportedSchema = Bottom[object, object, Never, Never] | A schema read from JSON Schema: nothing is known of its values statically, and it needs no services. |
PatternMode | type PatternMode = TypingLiteral['error', 'ignore', 'apply'] | |
Annotations | type Annotations = Mapping[str, object] | |
Check | type Check = Filter | FilterGroup | |
EnumValue | type EnumValue = str | int | float | |
Json | type Json = bool | int | float | str | list[Json] | dict[str, Json] | None | |
LiteralValue | type LiteralValue = str | int | float | bool | |
PropertyName | type PropertyName = str | int | float | |
References | type References = Mapping[str, Representation] | |
Representation | type Representation = Declaration | Reference | Suspend | Null | Undefined | Void | ObjectKeyword | Never | Unknown | Any | String | Number | Boolean | BigInt | Literal | Enum | TemplateLiteral | Arrays | Objects | Union | |
AnyReviver | type AnyReviver = DeclarationReviver[Any] | FilterReviver[Any] | FilterGroupReviver[Any] | |
AnySchema | type AnySchema = Bottom[object, object, object, object] | A revived schema: its node is known, its types are not (Effect's
|
Classes#
Functions#
make_code#
make_code(runtime, type) -> CodeCode(runtime, type) (Effect's makeCode).
| Parameter | Type | Description |
|---|---|---|
runtime | str | |
type | str |
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) -> CodeDocumentPython 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.
| Parameter | Type | Description |
|---|---|---|
document | R.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=()) -> strdocument 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.
| Parameter | Type | Description |
|---|---|---|
document | CodeDocument | |
names | Sequence[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" + bodyfrom_representation#
from_representation(document, /, *, revivers) -> AnySchemaThe schema document describes.
| Parameter | Type | Description |
|---|---|---|
document | R.Document | |
revivers | Sequence[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.
| Parameter | Type | Description |
|---|---|---|
document | R.MultiDocument | |
revivers | Sequence[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) -> ImportedSchemaThe 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".
| Parameter | Type | Description |
|---|---|---|
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 |
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.
| Parameter | Type | Description |
|---|---|---|
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 |
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.DocumentThe document input (to_json's output) holds.
| Parameter | Type | Description |
|---|---|---|
input | object |
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.MultiDocumentThe multi-document input (to_json_multi_document's output) holds.
| Parameter | Type | Description |
|---|---|---|
input | object |
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) -> Jsondocument as JSON.
| Parameter | Type | Description |
|---|---|---|
document | R.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) -> Jsondocument as JSON, its roots in order.
| Parameter | Type | Description |
|---|---|---|
document | R.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.
| Parameter | Type | Description |
|---|---|---|
document | R.Document | |
on_excess_property | OnExcessProperty = 'ignore' | |
generate_descriptions | bool = False | |
include_annotation_key | Callable[[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.
| Parameter | Type | Description |
|---|---|---|
document | R.MultiDocument | |
on_excess_property | OnExcessProperty = 'ignore' | |
generate_descriptions | bool = False | |
include_annotation_key | Callable[[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) -> MultiDocumentdocument as a multi-document of one root (Effect's
toMultiDocument).
| Parameter | Type | Description |
|---|---|---|
document | Document |
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.
| Parameter | Type | Description |
|---|---|---|
id | str | |
payload_schema | PayloadSchema[P] | |
revive | Callable[[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.
| Parameter | Type | Description |
|---|---|---|
id | str | |
payload_schema | PayloadSchema[P] | |
revive | Callable[[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.
| Parameter | Type | Description |
|---|---|---|
id | str | |
payload_schema | PayloadSchema[P] | |
revive | Callable[[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.DocumentThe 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.
| Parameter | Type | Description |
|---|---|---|
schema | Top | |
reference_policy | ReferencePolicy | 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.MultiDocumentThe documents of several schemas, sharing their references.
| Parameter | Type | Description |
|---|---|---|
schemas | tuple[Top, *(tuple[Top, ...])] | |
reference_policy | ReferencePolicy | 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)On This Page
Re-exportsValuesTypesClassesFunctionsmake_codeto_code_documentto_code_modulefrom_representationfrom_representationsfrom_json_schema_documentfrom_json_schema_multi_documentfrom_jsonfrom_json_multi_documentto_jsonto_json_multi_documentto_json_schema_documentto_json_schema_multi_documentto_multi_documentmake_reviver_declarationmake_reviver_filtermake_reviver_filter_groupto_representationto_representations