The schema AST (Effect's SchemaAST): one node per kind of value.
A schema object (Bottom) wraps one of these. Each node knows the text
of what it expects (get_expected, "string") and parses a value of
its own kind (parse), then runs its checks (Filter /
FilterGroup) on the value. annotations hold documentation and
message overrides (identifier, message, expected, ...), keyed
in snake_case.
Python mappings: Number accepts int and float (JavaScript has one
number type), BigInt accepts int, Null is None; bool is
neither a number nor a bigint. Enum is a Python enum.Enum, decoded
from its values. Symbol and UniqueSymbol have no Python counterpart; S.Undefined,
S.Void and S.ObjectKeyword are declarations here, not nodes.
Values#
| Attribute | Type | Description |
|---|---|---|
resolve_description | (AST) -> (str | None) | The node's |
resolve_identifier | (AST) -> (str | None) | The node's |
resolve_title | (AST) -> (str | None) | The node's |
STRUCTURAL | Literal['~structural'] = '~structural' | The annotation of a check of a value's shape (a length, a size, a key count): it holds on both sides of a composite whose parts transform. |
SENTINELS | Literal['~sentinels'] = '~sentinels' | The annotation of a declaration's sentinels: |
json | Declaration | Any JSON value ( |
string_tree | Declaration | Any string tree ( |
any_ | Any | |
big_int | BigInt | |
boolean | Boolean | |
never | Never | |
null | Null | |
number | Number | |
string | String | |
unknown | Unknown | |
whole_number | Number | |
MISSING | Missing | An absent value (see the module). |
MISSING_EXIT | Final[Success[object]] | |
BIG_INT_PATTERN | Literal['-?\\d+'] = '-?\\d+' | |
FINITE_PATTERN | Literal['[+-]?(?:\\d+(?:\\.\\d+)?|\\.\\d+)(?:[Ee][+-]?\\d+)?'] = '[+-]?(?:\\d+(?:\\.\\d+)?|\\.\\d+)(?:[Ee][+-]?\\d+)?' | Finite decimal text, with an optional exponent (Effect's |
STRING_PATTERN | Literal['[\\s\\S]*?'] = '[\\s\\S]*?' | Any text, newlines included (Effect's |
Types#
| Type | Definition | Description |
|---|---|---|
Annotations | type Annotations = Mapping[str, object] | |
Checks | type Checks = tuple[Check[Any], *(tuple[Check[Any], ...])] | The checks of a node, run in order on the value it parsed. |
Sentinel | type Sentinel = tuple[Hashable, LiteralValue] | A required key (or a tuple's index) and the literal it must hold. |
Check | type Check[T] = Filter[T] | FilterGroup[T] | |
FilterIssue | type FilterIssue = str | Issue | tuple[Path, str | Issue] | One failure a filter function reports: a message, an issue, or either
at a path below the value (Effect's |
FilterOutput | type FilterOutput = bool | FilterIssue | list[FilterIssue] | None | What a filter function gives: |
ClassSide | type ClassSide = _Literal['decode', 'encode', 'type', 'encoded'] | |
DeclarationParser | type DeclarationParser = Callable[[object, Declaration, ParseOptions], ParseResult] | |
DeclarationRun | type DeclarationRun = Callable[[tuple[AST, ...]], DeclarationParser] | |
Encoding | type Encoding = tuple[Link, *(tuple[Link, ...])] | |
EnumSide | type EnumSide = _Literal['decode', 'encode', 'type', 'encoded'] | |
LiteralValue | type LiteralValue = str | int | float | bool | None | |
ParseResult | type ParseResult = Exit[object, Issue] | Effect[object, Issue, Any] | A parse's outcome: an |
UnionMode | type UnionMode = _Literal['any_of', 'one_of'] |
Classes#
Functions#
is_optional#
is_optional(ast) -> boolA struct key holding ast may be missing (Effect's isOptional:
the node is optional_key).
| Parameter | Type | Description |
|---|---|---|
ast | AST |
Returns bool
def is_optional(ast: AST) -> bool:
"""A struct key holding ``ast`` may be missing (Effect's ``isOptional``:
the node is ``optional_key``)."""
return ast.optional_keyresolve_at#
resolve_at(key) -> Callable[[AST], object]The annotation key of the annotations describing a node (its last
check's when it has checks, else its own), or None (Effect's
resolveAt).
| Parameter | Type | Description |
|---|---|---|
key | str |
Returns Callable[[AST], object]
def resolve_at(key: str) -> Callable[[AST], object]:
"""The annotation ``key`` of the annotations describing a node (its last
check's when it has checks, else its own), or ``None`` (Effect's
``resolveAt``)."""
def at(ast: AST) -> object:
return (ast.resolve() or {}).get(key)
return atannotate#
annotate[N: AST](ast, annotations) -> Nast with annotations merged over its own; on a node with
checks they go to the last check, which then describes the node.
| Parameter | Type | Description |
|---|---|---|
ast | N | |
annotations | Annotations |
Returns N
def annotate[N: AST](ast: N, annotations: Annotations) -> N:
"""``ast`` with ``annotations`` merged over its own; on a node with
checks they go to the last check, which then describes the node."""
if ast.checks:
*rest, last = ast.checks
return replace_checks(ast, (*rest, last.annotate(**annotations)))
return copy(ast, annotations={**(ast.annotations or {}), **annotations})append_checks#
append_checks[N: AST](ast, checks) -> Nast with checks run after its own.
| Parameter | Type | Description |
|---|---|---|
ast | N | |
checks | Checks |
Returns N
def append_checks[N: AST](ast: N, checks: Checks) -> N:
"""``ast`` with ``checks`` run after its own."""
return replace_checks(ast, (*ast.checks, *checks) if ast.checks else checks)invalid_type#
invalid_type(ast, input, options) -> Failure[Issue]| Parameter | Type | Description |
|---|---|---|
ast | AST | |
input | object | |
options | ParseOptions |
Returns Failure[Issue]
def invalid_type(ast: AST, input: object, options: ParseOptions) -> Failure[Issue]:
return fail_exit(InvalidType(ast, reported(input, options)))issue_of#
issue_of(failure) -> Issue | NoneThe issue of a failed parse, or None when its cause holds
anything else (a defect is never a mismatch).
| Parameter | Type | Description |
|---|---|---|
failure | Failure[Issue] |
Returns Issue | None
def issue_of(failure: Failure[Issue]) -> Issue | None:
"""The issue of a failed parse, or ``None`` when its cause holds
anything else (a defect is never a mismatch)."""
reasons = failure.cause.reasons
if reasons and all(isinstance(r, Fail) and is_issue(r.error) for r in reasons):
first = reasons[0]
return first.error if isinstance(first, Fail) else None
return Nonejoin_checks#
join_checks(first, second) -> Checks | None| Parameter | Type | Description |
|---|---|---|
first | Checks | None | |
second | Checks | None |
Returns Checks | None
def join_checks(first: Checks | None, second: Checks | None) -> Checks | None:
if first is None:
return second
if second is None:
return first
return (*first, *second)map_or_same#
map_or_same[A](items, f) -> tuple[A, ...]f of each item, or items itself when f returns every item
unchanged (is), Effect's mapOrSame.
| Parameter | Type | Description |
|---|---|---|
items | tuple[A, ...] | |
f | Callable[[A], A] |
Returns tuple[A, ...]
def map_or_same[A](items: tuple[A, ...], f: Callable[[A], A]) -> tuple[A, ...]:
"""``f`` of each item, or ``items`` itself when ``f`` returns every item
unchanged (``is``), Effect's ``mapOrSame``."""
out: list[A] | None = None
for i, item in enumerate(items):
mapped = f(item)
if out is not None:
out.append(mapped)
elif mapped is not item:
out = [*items[:i], mapped]
return items if out is None else tuple(out)replace_checks#
replace_checks[N: AST](ast, checks) -> Nast with checks in place of its own; ast itself when they
are the same tuple. A Suspend takes no checks (its target does).
| Parameter | Type | Description |
|---|---|---|
ast | N | |
checks | Checks | None |
Returns N
def replace_checks[N: AST](ast: N, checks: Checks | None) -> N:
"""``ast`` with ``checks`` in place of its own; ``ast`` itself when they
are the same tuple. A ``Suspend`` takes no checks (its target does)."""
if ast.tag == "Suspend" and checks:
raise ValueError("Cannot add checks to Suspend")
return ast if ast.checks is checks else copy(ast, checks=checks)replace_context#
replace_context[A: AST](node, *, key_annotations=None, optional_key=None) -> Anode with another key context (Effect's replaceContext): a
copy sharing node's body (its owner), node itself when the
context is its own, or the owner when the context is the owner's.
| Parameter | Type | Description |
|---|---|---|
node | A | |
key_annotations | Annotations | None = None | |
optional_key | bool | None = None |
Returns A
def replace_context[A: AST](
node: A, *, key_annotations: Annotations | None = None, optional_key: bool | None = None
) -> A:
"""``node`` with another key context (Effect's ``replaceContext``): a
copy sharing ``node``'s body (its ``owner``), ``node`` itself when the
context is its own, or the owner when the context is the owner's."""
return _in_context(
node,
node.key_annotations if key_annotations is None else key_annotations,
node.optional_key if optional_key is None else optional_key,
node.constructor_default,
)replace_encoding#
replace_encoding[N: AST](ast, encoding) -> Nast decoding through encoding instead of its own; ast
itself when it is the same.
| Parameter | Type | Description |
|---|---|---|
ast | N | |
encoding | Encoding | None |
Returns N
def replace_encoding[N: AST](ast: N, encoding: Encoding | None) -> N:
"""``ast`` decoding through ``encoding`` instead of its own; ``ast``
itself when it is the same."""
return ast if ast.encoding is encoding else copy(ast, encoding=encoding)structural_checks#
structural_checks(checks) -> Checks | NoneThe structural checks among checks, a group's structural members
taken out of it (Effect's extractStructuralChecks).
| Parameter | Type | Description |
|---|---|---|
checks | Checks |
Returns Checks | None
def structural_checks(checks: Checks) -> Checks | None:
"""The structural checks among ``checks``, a group's structural members
taken out of it (Effect's ``extractStructuralChecks``)."""
out: list[Check[Any]] = []
_extract_structural(checks, out)
return (out[0], *out[1:]) if out else Nonewith_constructor_default#
with_constructor_default[A: AST](ast, default) -> Aast whose missing key or element a constructor fills with
default's value (Effect's SchemaAST.withConstructorDefault); the
copy shares ast's body.
| Parameter | Type | Description |
|---|---|---|
ast | A | |
default | Effect[object, Issue] |
Returns A
def with_constructor_default[A: AST](ast: A, default: Effect[object, Issue]) -> A:
"""``ast`` whose missing key or element a constructor fills with
``default``'s value (Effect's ``SchemaAST.withConstructorDefault``); the
copy shares ``ast``'s body."""
require_effect(default, "default")
return _in_context(ast, ast.key_annotations, ast.optional_key, default)collect_sentinels#
collect_sentinels(ast) -> tuple[Sentinel, ...]The required literal keys of a mapping node and the required literal
elements of a tuple, by index (Effect's collectSentinels); a union's
are those all its members share, a declaration's its "~sentinels"
annotation.
| Parameter | Type | Description |
|---|---|---|
ast | AST |
Returns tuple[Sentinel, ...]
def collect_sentinels(ast: AST) -> tuple[Sentinel, ...]:
"""The required literal keys of a mapping node and the required literal
elements of a tuple, by index (Effect's ``collectSentinels``); a union's
are those all its members share, a declaration's its ``"~sentinels"``
annotation."""
return _sentinels(ast, _Memo())collect_issues#
collect_issues(checks, value, ast, options) -> tuple[Issue, *(tuple[Issue, ...])] | NoneThe failures of checks on value, or None.
| Parameter | Type | Description |
|---|---|---|
checks | Sequence[Check[object]] | |
value | object | |
ast | AST | |
options | ParseOptions |
Returns tuple[Issue, *(tuple[Issue, ...])] | None
def collect_issues(
checks: Sequence[Check[object]], value: object, ast: AST, options: ParseOptions
) -> tuple[Issue, *tuple[Issue, ...]] | None:
"""The failures of ``checks`` on ``value``, or ``None``."""
issues: list[_issue.Filter] = []
_collect(checks, value, ast, options, issues)
return (issues[0], *issues[1:]) if issues else Nonefilter_of#
filter_of[T](predicate, annotations=None, abort=False) -> Filter[T]make_filter with the annotations as one mapping.
| Parameter | Type | Description |
|---|---|---|
predicate | Callable[[T], FilterOutput] | |
annotations | Annotations | None = None | |
abort | bool = False |
Returns Filter[T]
def filter_of[T](
predicate: Callable[[T], FilterOutput],
annotations: Annotations | None = None,
abort: bool = False,
) -> Filter[T]:
"""``make_filter`` with the annotations as one mapping."""
def run(input: T, ast: AST, options: ParseOptions) -> Issue | None:
return normalize_filter_output(ast, predicate(input), input, options)
return Filter(run, annotations, abort)has_check#
has_check(checks, id) -> boolWhether a check with the representation id id is among
checks or the groups inside them (Effect's hasCheck).
| Parameter | Type | Description |
|---|---|---|
checks | Sequence[Check[Any]] | None | |
id | str |
Returns bool
def has_check(checks: Sequence[Check[Any]] | None, id: str) -> bool:
"""Whether a check with the ``representation`` id ``id`` is among
``checks`` or the groups inside them (Effect's ``hasCheck``)."""
for check in checks or ():
if isinstance(check, FilterGroup):
if has_check(check.checks, id):
return True
continue
representation = (check.annotations or {}).get("representation")
if isinstance(representation, Mapping) and representation.get("id") == id: # pyright: ignore[reportUnknownMemberType]
return True
return Falsemake_filter#
make_filter[T](predicate, /, *, abort=False, **annotations) -> Filter[T]A filter from a function returning a FilterOutput (Effect's
makeFilter).
| Parameter | Type | Description |
|---|---|---|
predicate | Callable[[T], FilterOutput] | |
abort | bool = False | |
annotations | object = {} |
Returns Filter[T]
def make_filter[T](
predicate: Callable[[T], FilterOutput], /, *, abort: bool = False, **annotations: object
) -> Filter[T]:
"""A filter from a function returning a ``FilterOutput`` (Effect's
``makeFilter``)."""
return filter_of(predicate, annotations or None, abort)make_filter_by_guard#
make_filter_by_guard[T](guard, annotations=None) -> Filter[T]A filter accepting what guard accepts; it always aborts, as the
checks after a guard may rely on it.
| Parameter | Type | Description |
|---|---|---|
guard | Callable[[T], bool] | |
annotations | Annotations | None = None |
Returns Filter[T]
def make_filter_by_guard[T](
guard: Callable[[T], bool], annotations: Annotations | None = None
) -> Filter[T]:
"""A filter accepting what ``guard`` accepts; it always aborts, as the
checks after a guard may rely on it."""
def run(input: T, ast: AST, options: ParseOptions) -> Issue | None:
return None if guard(input) else InvalidValue(None, reported(input, options))
return Filter(run, annotations, True)normalize_filter_output#
normalize_filter_output(ast, out, input, options) -> Issue | NoneThe issue a filter function's output stands for, or None.
| Parameter | Type | Description |
|---|---|---|
ast | AST | |
out | FilterOutput | |
input | object | |
options | ParseOptions |
Returns Issue | None
def normalize_filter_output(
ast: AST, out: FilterOutput, input: object, options: ParseOptions
) -> Issue | None:
"""The issue a filter function's output stands for, or ``None``."""
if out is None or out is True:
return None
if out is False:
return InvalidValue(None, reported(input, options))
if not isinstance(out, list):
return _filter_issue(out, input, options)
issues = [_filter_issue(entry, input, options) for entry in out]
if not issues:
return None
if len(issues) == 1:
return issues[0]
return Composite(ast, (issues[0], *issues[1:]), reported(input, options))check_instance#
check_instance(shape, instance, options) -> Exit[object, Issue]instance after the class's own checks.
| Parameter | Type | Description |
|---|---|---|
shape | ClassShape | |
instance | object | |
options | ParseOptions |
Returns Exit[object, Issue]
def check_instance(
shape: ClassShape, instance: object, options: ParseOptions
) -> Exit[object, Issue]:
"""``instance`` after the class's own checks."""
checks = shape.checks
if checks is None or options.get("disable_checks"):
return Success(instance)
try:
issues = collect_issues(checks, instance, shape.fields, options)
except Exception as defect:
return die_exit(defect)
if issues is None:
return Success(instance)
return fail_exit(Composite(shape.fields, issues, reported(instance, options)))struct#
struct(fields, checks=None, annotations=None) -> ObjectsA struct of fields, keys in order; a field is optional when its
node is optional_key.
| Parameter | Type | Description |
|---|---|---|
fields | Mapping[str, AST] | |
checks | Checks | None = None | |
annotations | Annotations | None = None |
Returns Objects
def struct(
fields: Mapping[str, AST], checks: Checks | None = None, annotations: Annotations | None = None
) -> Objects:
"""A struct of ``fields``, keys in order; a field is optional when its
node is ``optional_key``."""
return Objects(
tuple(PropertySignature(name, node, node.optional_key) for name, node in fields.items()),
annotations=annotations,
checks=checks,
)struct_with_rest#
struct_with_rest(ast, records) -> Objectsast's keys and every record's keys and key patterns, with all
their checks. A node with an encoding raises ValueError, as does a
key two of them declare.
| Parameter | Type | Description |
|---|---|---|
ast | Objects | |
records | Sequence[Objects] |
Returns Objects
def struct_with_rest(ast: Objects, records: Sequence[Objects]) -> Objects:
"""``ast``'s keys and every record's keys and key patterns, with all
their checks. A node with an encoding raises ``ValueError``, as does a
key two of them declare."""
if ast.encoding is not None or any(r.encoding is not None for r in records):
raise ValueError("StructWithRest does not support encodings")
properties = list(ast.properties)
index_signatures = list(ast.index_signatures)
checks = ast.checks
for record in records:
for p in record.properties:
if any(q.name == p.name for q in properties):
raise ValueError(f"Duplicate identifier: {_json_text.stringify(p.name)}. ts(2300)")
properties += record.properties
index_signatures += record.index_signatures
checks = join_checks(checks, record.checks)
return Objects(tuple(properties), tuple(index_signatures), checks=checks)tuple_#
tuple_(elements, checks=None) -> ArraysA fixed tuple of elements; an element is optional when its node
is optional_key.
| Parameter | Type | Description |
|---|---|---|
elements | Sequence[AST] | |
checks | Checks | None = None |
Returns Arrays
def tuple_(elements: Sequence[AST], checks: Checks | None = None) -> Arrays:
"""A fixed tuple of ``elements``; an element is optional when its node
is ``optional_key``."""
return Arrays(tuple(Element(node, node.optional_key) for node in elements), checks=checks)tuple_with_rest#
tuple_with_rest(ast, rest) -> Arraysast's elements, then rest (see Arrays), with its checks;
a node with an encoding raises ValueError.
| Parameter | Type | Description |
|---|---|---|
ast | Arrays | |
rest | Sequence[AST] |
Returns Arrays
def tuple_with_rest(ast: Arrays, rest: Sequence[AST]) -> Arrays:
"""``ast``'s elements, then ``rest`` (see ``Arrays``), with its checks;
a node with an encoding raises ``ValueError``."""
if ast.encoding is not None:
raise ValueError("TupleWithRest does not support encodings")
return Arrays(ast.elements, tuple(rest), ast.mutable, checks=ast.checks)union#
union(members, mode='any_of', checks=None) -> UnionA union of members in order.
| Parameter | Type | Description |
|---|---|---|
members | Sequence[AST] | |
mode | UnionMode = 'any_of' | |
checks | Checks | None = None |
Returns Union
def union(
members: Sequence[AST], mode: UnionMode = "any_of", checks: Checks | None = None
) -> Union:
"""A union of ``members`` in order."""
return Union(tuple(members), mode, checks=checks)parse_at_key#
parse_at_key(ast, key, node, value, *, input, options) -> ParseResultvalue (input's part at key) parsed by node; an issue
is reported as ast's at key (Effect's makeCompositeAtKey).
| Parameter | Type | Description |
|---|---|---|
ast | AST | |
key | Hashable | |
node | AST | |
value | object | |
input | object | |
options | ParseOptions |
Returns ParseResult
def parse_at_key(
ast: AST,
key: Hashable,
node: AST,
value: object,
*,
input: object,
options: ParseOptions,
) -> ParseResult:
"""``value`` (``input``'s part at ``key``) parsed by ``node``; an issue
is reported as ``ast``'s at ``key`` (Effect's ``makeCompositeAtKey``)."""
def at_key(exit: Exit[object, Issue]) -> Exit[object, Issue]:
if type(exit) is Success:
return exit
failure = cast("Failure[Issue]", exit)
issue = issue_of(failure)
if issue is None:
return failure
return fail_exit(Composite(ast, (Pointer((key,), issue),), reported(input, options)))
return then(node.parse(value, options), at_key)decode_to#
decode_to[A: AST](from_, to, transformation) -> Ato, decoding from values of from_ through transformation
(Effect's decodeTo): a link appended to to's encoding.
| Parameter | Type | Description |
|---|---|---|
from_ | AST | |
to | A | |
transformation | LinkTransformation |
Returns A
def decode_to[A: AST](from_: AST, to: A, transformation: LinkTransformation) -> A:
"""``to``, decoding from values of ``from_`` through ``transformation``
(Effect's ``decodeTo``): a link appended to ``to``'s encoding."""
link = Link(from_, transformation)
out = replace(to, encoding=(*to.encoding, link) if to.encoding else (link,))
object.__setattr__(out, "body_owner", to.body_owner or to.owner())
return outoptional_key#
optional_key[A: AST](ast) -> Aast as a struct key that may be missing on the encoded side, down
to its most encoded node (Effect's optionalKey).
| Parameter | Type | Description |
|---|---|---|
ast | A |
Returns A
def optional_key[A: AST](ast: A) -> A:
"""``ast`` as a struct key that may be missing on the encoded side, down
to its most encoded node (Effect's ``optionalKey``)."""
# _base imports this module.
from pyfect.schema.ast._base import replace_context
encoding = ast.encoding
if encoding is None:
return ast if ast.optional_key else replace_context(ast, optional_key=True)
last = encoding[-1]
chain: Encoding = (*encoding[:-1], Link(optional_key(last.to), last.transformation))
return replace(ast, encoding=chain, optional_key=True)to_encoded#
to_encoded(ast) -> ASTThe node's encoded side, as a node of its own (Effect's toEncoded):
made once, and its own encoded side.
| Parameter | Type | Description |
|---|---|---|
ast | AST |
Returns AST
def to_encoded(ast: AST) -> AST:
"""The node's encoded side, as a node of its own (Effect's ``toEncoded``):
made once, and its own encoded side."""
memo = ast._encoded_side # pyright: ignore[reportPrivateUsage]
if not memo:
encoded = ast.flip().to_type()
memo.append(encoded)
own = encoded._encoded_side # pyright: ignore[reportPrivateUsage]
if not own:
own.append(encoded)
return memo[0]is_json#
is_json(value) -> boolvalue is None, a string, a boolean, an int, a finite
float, or a list / tuple / string-keyed Mapping of JSON
values. A cycle is not JSON; a value shared twice (a DAG) is. Iterative,
so any depth works.
| Parameter | Type | Description |
|---|---|---|
value | object |
Returns bool
def is_json(value: object) -> bool:
"""``value`` is ``None``, a string, a boolean, an ``int``, a finite
``float``, or a ``list`` / ``tuple`` / string-keyed ``Mapping`` of JSON
values. A cycle is not JSON; a value shared twice (a DAG) is. Iterative,
so any depth works."""
return _is_tree(value, _is_json_leaf)is_string_tree#
is_string_tree(value) -> boolvalue is a string, None (Effect's undefined), or a
list / tuple / string-keyed Mapping of string trees (Effect's
isStringTree); a cycle is not one.
| Parameter | Type | Description |
|---|---|---|
value | object |
Returns bool
def is_string_tree(value: object) -> bool:
"""``value`` is a string, ``None`` (Effect's ``undefined``), or a
``list`` / ``tuple`` / string-keyed ``Mapping`` of string trees (Effect's
``isStringTree``); a cycle is not one."""
return _is_tree(value, _is_string_tree_leaf)format_literal#
format_literal(literal) -> strA literal as Effect prints it: strings quoted, null, true.
| Parameter | Type | Description |
|---|---|---|
literal | LiteralValue |
Returns str
def format_literal(literal: LiteralValue) -> str:
"""A literal as Effect prints it: strings quoted, ``null``, ``true``."""
match literal:
case None:
return "null"
case bool():
return "true" if literal else "false"
case int() | float():
return js_number(literal)
case str():
return json_quote(literal)same_literal#
same_literal(literal, input) -> boolinput is literal, as JavaScript's === reads them.
| Parameter | Type | Description |
|---|---|---|
literal | LiteralValue | |
input | object |
Returns bool
def same_literal(literal: LiteralValue, input: object) -> bool:
"""``input`` is ``literal``, as JavaScript's ``===`` reads them."""
match literal:
case None:
return input is None
case bool():
return isinstance(input, bool) and input == literal
case int() | float():
return (
isinstance(input, (int, float)) and not isinstance(input, bool) and input == literal
)
case str():
return isinstance(input, str) and input == literalget_index_signature_keys#
get_index_signature_keys(input, parameter, options=None) -> list[Any]The keys of input that an index signature with parameter
takes (Effect's getIndexSignatureKeys): those its encoded side
accepts. A union's are its members' in member order, each key once.
| Parameter | Type | Description |
|---|---|---|
input | Mapping[Any, object] | |
parameter | AST | |
options | ParseOptions | None = None |
Returns list[Any]
def get_index_signature_keys(
input: Mapping[Any, object], parameter: AST, options: ParseOptions | None = None
) -> list[Any]:
"""The keys of ``input`` that an index signature with ``parameter``
takes (Effect's ``getIndexSignatureKeys``): those its encoded side
accepts. A union's are its members' in member order, each key once."""
return _index_signature_keys(input, to_encoded(parameter), options or {})record#
record(key, value) -> ObjectsEffect's record: each literal key (a Literal, or one in a
union) is a required property, listed once; any other key node is an
index signature. Never takes no key.
| Parameter | Type | Description |
|---|---|---|
key | AST | |
value | AST |
Returns Objects
def record(key: AST, value: AST) -> Objects:
"""Effect's ``record``: each literal key (a ``Literal``, or one in a
union) is a required property, listed once; any other key node is an
index signature. ``Never`` takes no key."""
literals: list[LiteralValue] = []
parameters: list[AST] = []
_split_keys(key, literals, parameters)
return Objects(
tuple(PropertySignature(name, value) for name in literals),
tuple(IndexSignature(parameter, value) for parameter in parameters),
)call#
call[*Ts](f, *args) -> ParseResultf(*args), a user callback (a getter's function, a middleware):
a raise is a defect, as in Effect.
| Parameter | Type | Description |
|---|---|---|
f | Callable[[*Ts], ParseResult] | |
args | *Ts = () |
Returns ParseResult
def call[*Ts](f: Callable[[*Ts], ParseResult], /, *args: *Ts) -> ParseResult:
"""``f(*args)``, a user callback (a getter's function, a middleware):
a raise is a defect, as in Effect."""
try:
return f(*args)
except Exception as defect:
return die_exit(defect)flat_map#
flat_map(result, f) -> ParseResultf of the parsed value; a failure stays as it is.
| Parameter | Type | Description |
|---|---|---|
result | ParseResult | |
f | Callable[[object], ParseResult] |
Returns ParseResult
def flat_map(result: ParseResult, f: Callable[[object], ParseResult]) -> ParseResult:
"""``f`` of the parsed value; a failure stays as it is."""
if isinstance(result, Success):
return f(result.value)
if isinstance(result, Failure):
return result
return result.flat_map(lambda value: to_effect(f(value)))is_exit#
is_exit(result) -> TypeIs[Exit[object, Issue]]| Parameter | Type | Description |
|---|---|---|
result | ParseResult |
Returns TypeIs[Exit[object, Issue]]
def is_exit(result: ParseResult) -> TypeIs[Exit[object, Issue]]:
return isinstance(result, (Success, Failure))map_issue#
map_issue(result, f) -> ParseResultEach issue of a failure changed by f; defects stay.
| Parameter | Type | Description |
|---|---|---|
result | ParseResult | |
f | Callable[[Issue], Issue] |
Returns ParseResult
def map_issue(result: ParseResult, f: Callable[[Issue], Issue]) -> ParseResult:
"""Each issue of a failure changed by ``f``; defects stay."""
if isinstance(result, Success):
return result
if isinstance(result, Failure):
return Failure(result.cause.map(f))
return result.map_error(f)map_value#
map_value(result, f) -> ParseResultThe parsed value changed by f.
| Parameter | Type | Description |
|---|---|---|
result | ParseResult | |
f | Callable[[object], object] |
Returns ParseResult
def map_value(result: ParseResult, f: Callable[[object], object]) -> ParseResult:
"""The parsed value changed by ``f``."""
if isinstance(result, Success):
return Success(f(result.value))
if isinstance(result, Failure):
return result
return result.map(f)run_now#
run_now(result) -> Exit[object, Issue]The outcome, running an effect to its end on this thread (for the synchronous adapters and checks; its services must be provided).
| Parameter | Type | Description |
|---|---|---|
result | ParseResult |
Returns Exit[object, Issue]
def run_now(result: ParseResult) -> Exit[object, Issue]:
"""The outcome, running an effect to its end on this thread (for the
synchronous adapters and checks; its services must be provided)."""
if isinstance(result, (Success, Failure)):
return result
return run_sync_exit(cast("Effect[object, Issue, Never]", result))then#
then(result, f) -> ParseResultf of the outcome, whichever it is: called now for an Exit,
when the effect ends otherwise.
| Parameter | Type | Description |
|---|---|---|
result | ParseResult | |
f | Callable[[Exit[object, Issue]], ParseResult] |
Returns ParseResult
def then(result: ParseResult, f: Callable[[Exit[object, Issue]], ParseResult]) -> ParseResult:
"""``f`` of the outcome, whichever it is: called now for an ``Exit``,
when the effect ends otherwise."""
if isinstance(result, (Success, Failure)):
return f(result)
return result.exit().flat_map(lambda exit: to_effect(f(exit)))to_effect#
to_effect(result) -> Effect[object, Issue, Any]| Parameter | Type | Description |
|---|---|---|
result | ParseResult |
Returns Effect[object, Issue, Any]
def to_effect(result: ParseResult) -> Effect[object, Issue, Any]:
if isinstance(result, (Success, Failure)):
return from_exit(result)
return resultmatch_part#
match_part(node, text, options) -> booltext is a segment of the part node (Effect's matchPart).
| Parameter | Type | Description |
|---|---|---|
node | AST | |
text | str | |
options | ParseOptions |
Returns bool
def match_part(node: AST, text: str, options: ParseOptions) -> bool:
"""``text`` is a segment of the part ``node`` (Effect's ``matchPart``)."""
return _match_span(node, text, 0, len(text), options)On This Page
ValuesTypesClassesFunctionsis_optionalresolve_atannotateappend_checksinvalid_typeissue_ofjoin_checksmap_or_samereplace_checksreplace_contextreplace_encodingstructural_checkswith_constructor_defaultcollect_sentinelscollect_issuesfilter_ofhas_checkmake_filtermake_filter_by_guardnormalize_filter_outputcheck_instancestructstruct_with_resttuple_tuple_with_restunionparse_at_keydecode_tooptional_keyto_encodedis_jsonis_string_treeformat_literalsame_literalget_index_signature_keysrecordcallflat_mapis_exitmap_issuemap_valuerun_nowthento_effectmatch_part