Getters (Effect's SchemaGetter): one direction of a
transformation. A Getter[T, E, R] turns a value of E, or a missing
one, into a value of T or none, maybe needing services R::
from pyfect.schema import getter as G
G.transform(int) # a present value through a function
G.with_default(Success(0)) # a missing value replaced
G.number().compose(G.transform(abs))A transformation (pyfect.schema.transformation) pairs a decoding
getter with an encoding one. run(getter, Some(value), {}) runs one.
Values#
| Attribute | Type | Description |
|---|---|---|
forbidden_encoding | Getter[Never, object] | Encoding fails with |
Types#
| Type | Definition | Description |
|---|---|---|
Outcome | type Outcome[T, R = Never] = Effect[T, Issue, R] | Exit[T, Issue] | What an effectful getter's function gives: an |
Tag | type Tag = Literal['Passthrough', 'Transform', 'TransformOptional', 'TransformEffect', 'TransformOptionalEffect'] | |
JsonReplacer | type JsonReplacer = Callable[[str, object], object] | list[str | int] | tuple[str | int, ...] | A function called with each key ( |
JsonReviver | type JsonReviver = Callable[[str, object], object] | Called with each key ( |
CheckOutput | type CheckOutput = bool | FilterIssue | None |
Classes#
Functions#
decode_base64#
decode_base64() -> Getter[bytes, str]Returns Getter[bytes, str]
def decode_base64() -> Getter[bytes, str]:
return _decoder(base64_decode, "a valid Base64 string", _same)decode_base64_string#
decode_base64_string() -> Getter[str, str]Returns Getter[str, str]
def decode_base64_string() -> Getter[str, str]:
return _decoder(base64_decode, "a valid Base64 string", _text)decode_base64_url#
decode_base64_url() -> Getter[bytes, str]Returns Getter[bytes, str]
def decode_base64_url() -> Getter[bytes, str]:
return _decoder(base64_url_decode, "a valid Base64Url string", _same)decode_base64_url_string#
decode_base64_url_string() -> Getter[str, str]Returns Getter[str, str]
def decode_base64_url_string() -> Getter[str, str]:
return _decoder(base64_url_decode, "a valid Base64Url string", _text)decode_hex#
decode_hex() -> Getter[bytes, str]Returns Getter[bytes, str]
def decode_hex() -> Getter[bytes, str]:
return _decoder(hex_decode, "a valid hexadecimal string", _same)decode_hex_string#
decode_hex_string() -> Getter[str, str]Returns Getter[str, str]
def decode_hex_string() -> Getter[str, str]:
return _decoder(hex_decode, "a valid hexadecimal string", _text)encode_base64#
encode_base64() -> Getter[str, bytes | str]Returns Getter[str, bytes | str]
def encode_base64() -> Getter[str, bytes | str]:
return Transform(base64_encode)encode_base64_url#
encode_base64_url(*, padding=False) -> Getter[str, bytes | str]Unpadded unless padding.
| Parameter | Type | Description |
|---|---|---|
padding | bool = False |
Returns Getter[str, bytes | str]
def encode_base64_url(*, padding: bool = False) -> Getter[str, bytes | str]:
"""Unpadded unless ``padding``."""
return Transform(lambda value: base64_url_encode(value, padding=padding))encode_hex#
encode_hex() -> Getter[str, bytes | str]Returns Getter[str, bytes | str]
def encode_hex() -> Getter[str, bytes | str]:
return Transform(hex_encode)big_int#
big_int() -> Getter[int, str | int | float | bool]BigInt(value); what it rejects is an InvalidValue (Effect's
SchemaGetter.BigInt).
Returns Getter[int, str | int | float | bool]
def big_int() -> Getter[int, str | int | float | bool]:
"""``BigInt(value)``; what it rejects is an ``InvalidValue`` (Effect's
``SchemaGetter.BigInt``)."""
def run(value: object, options: ParseOptions) -> Exit[int, Issue]:
out = to_big_int(value)
if out is None:
expected = {"expected": "a value that can be converted to a bigint"}
return fail_exit(InvalidValue(expected, reported(value, options)))
return Success(out)
return TransformEffect(run)boolean#
boolean() -> Getter[bool, object]Boolean(value) (Effect's SchemaGetter.Boolean).
Returns Getter[bool, object]
def boolean() -> Getter[bool, object]:
"""``Boolean(value)`` (Effect's ``SchemaGetter.Boolean``)."""
return Transform(to_boolean)date_time_utc_from_input#
date_time_utc_from_input() -> Getter[datetime, object]A UTC datetime from a DateTime.Input (see to_utc); an
InvalidValue otherwise (Effect's dateTimeUtcFromInput).
Returns Getter[datetime, object]
def date_time_utc_from_input() -> Getter[datetime, object]:
"""A UTC ``datetime`` from a ``DateTime.Input`` (see ``to_utc``); an
``InvalidValue`` otherwise (Effect's ``dateTimeUtcFromInput``)."""
def run(value: object, options: ParseOptions) -> Exit[datetime, Issue]:
out = to_utc(value)
if out is None:
message: dict[str, Any] = {"message": "Invalid DateTime input"}
return fail_exit(InvalidValue(message, reported(value, options)))
return Success(out)
return TransformEffect(run)number#
number() -> Getter[float, object]Number(value) (Effect's SchemaGetter.Number).
Returns Getter[float, object]
def number() -> Getter[float, object]:
"""``Number(value)`` (Effect's ``SchemaGetter.Number``)."""
return Transform(to_number)parse_json#
parse_json() -> Getter[_json.Json, str]
parse_json(*, reviver: JsonReviver) -> Getter[object, str]The JSON value of a string (JSON.parse), walked by reviver
when given; an InvalidValue when it is not JSON or reviver
raises (Effect's parseJson).
| Parameter | Type | Description |
|---|---|---|
reviver | = None |
@overload
def parse_json() -> Getter[_json.Json, str]: ...
@overload
def parse_json(*, reviver: JsonReviver) -> Getter[object, str]: ...
def parse_json(*, reviver: JsonReviver | None = None) -> Getter[object, str]:
"""The JSON value of a string (``JSON.parse``), walked by ``reviver``
when given; an ``InvalidValue`` when it is not JSON or ``reviver``
raises (Effect's ``parseJson``)."""
def run(text: str, options: ParseOptions) -> Exit[object, Issue]:
try:
value = _json.parse(text)
return Success(value if reviver is None else revive(value, reviver))
except Exception:
# Effect's ``Effect.try`` turns whatever ``JSON.parse`` throws, a reviver's error
# included, into this issue.
expected = {"expected": "a valid JSON string"}
return fail_exit(InvalidValue(expected, reported(text, options)))
return TransformEffect(run)string#
string() -> Getter[str, object]String(value) (Effect's SchemaGetter.String).
Returns Getter[str, object]
def string() -> Getter[str, object]:
"""``String(value)`` (Effect's ``SchemaGetter.String``)."""
return Transform(to_string)stringify_json#
stringify_json(*, replacer=None, space=None) -> Getter[str, object]The JSON text of a value (JSON.stringify, through replacer
and indented by space; NaN and infinities as null); an
InvalidValue when it has none or replacer raises (Effect's
stringifyJson).
| Parameter | Type | Description |
|---|---|---|
replacer | JsonReplacer | None = None | |
space | int | str | None = None |
Returns Getter[str, object]
def stringify_json(
*, replacer: JsonReplacer | None = None, space: int | str | None = None
) -> Getter[str, object]:
"""The JSON text of a value (``JSON.stringify``, through ``replacer``
and indented by ``space``; ``NaN`` and infinities as ``null``); an
``InvalidValue`` when it has none or ``replacer`` raises (Effect's
``stringifyJson``)."""
def run(value: object, options: ParseOptions) -> Exit[str, Issue]:
try:
replaced = value if replacer is None else replace_json(value, replacer)
return Success(_json.stringify(replaced, indent=space))
except Exception:
expected = {"expected": "a JSON-serializable value"}
return fail_exit(InvalidValue(expected, reported(value, options)))
return TransformEffect(run)run#
run[T, E, R](getter, input, options) -> Effect[Option[T], Issue, R]The getter's output for input (Effect's SchemaGetter.run).
| Parameter | Type | Description |
|---|---|---|
getter | Getter[T, E, R] | |
input | Option[E] | |
options | ParseOptions |
Returns Effect[Option[T], Issue, R]
def run[T, E, R](
getter: Getter[T, E, R], input: Option[E], options: ParseOptions
) -> Effect[Option[T], Issue, R]:
"""The getter's output for ``input`` (Effect's ``SchemaGetter.run``)."""
result = getter.apply(_value(cast("Option[object]", input)), options)
return cast("Effect[Option[T], Issue, R]", to_effect(map_value(result, _option)))check_effect#
check_effect[T, R = Never](f) -> Getter[T, T, R]The value, once the effect f makes accepts it: None / True
pass, False is an InvalidValue, a string its message, an issue
itself (Effect's checkEffect). f may need services.
| Parameter | Type | Description |
|---|---|---|
f | Callable[[T, ParseOptions], Effect[CheckOutput, Never, R]] |
Returns Getter[T, T, R]
def check_effect[T, R = Never](
f: Callable[[T, ParseOptions], Effect[CheckOutput, Never, R]], /
) -> Getter[T, T, R]:
"""The value, once the effect ``f`` makes accepts it: ``None`` / ``True``
pass, ``False`` is an ``InvalidValue``, a string its message, an issue
itself (Effect's ``checkEffect``). ``f`` may need services."""
def run(value: T, options: ParseOptions) -> Effect[T, Issue, R]:
def decide(out: CheckOutput) -> Outcome[T]:
issue = normalize_filter_output(unknown, out, value, options)
return Success(value) if issue is None else fail_exit(issue)
return f(value, options).flat_map(lambda out: _effect(decide(out)))
return TransformEffect(run)fail#
fail[E](f) -> Getter[Never, E]Always the issue f makes (Effect's fail).
| Parameter | Type | Description |
|---|---|---|
f | Callable[[Option[E], ParseOptions], Issue] |
Returns Getter[Never, E]
def fail[E](f: Callable[[Option[E], ParseOptions], Issue], /) -> Getter[Never, E]:
"""Always the issue ``f`` makes (Effect's ``fail``)."""
return TransformOptionalEffect(lambda input, options: fail_exit(f(input, options)))forbidden#
forbidden[E](message) -> Getter[Never, E]Always a Forbidden issue with message (Effect's forbidden).
| Parameter | Type | Description |
|---|---|---|
message | Callable[[Option[E]], str] |
Returns Getter[Never, E]
def forbidden[E](message: Callable[[Option[E]], str], /) -> Getter[Never, E]:
"""Always a ``Forbidden`` issue with ``message`` (Effect's ``forbidden``)."""
def issue(input: Option[E], options: ParseOptions) -> Issue:
annotations = {"message": message(input)}
if input is None:
return Forbidden(annotations)
return Forbidden(annotations, reported(input.value, options))
return fail(issue)omit#
omit() -> Getter[Never, object]No output: the key is left out (Effect's omit).
Returns Getter[Never, object]
def omit() -> Getter[Never, object]:
"""No output: the key is left out (Effect's ``omit``)."""
return TransformOptional(lambda _: None)passthrough#
passthrough[T]() -> Getter[T, T]The input, unchanged (Effect's passthrough).
Returns Getter[T, T]
def passthrough[T]() -> Getter[T, T]:
"""The input, unchanged (Effect's ``passthrough``)."""
return PASSTHROUGHpassthrough_subtype#
passthrough_subtype() -> Getter[Any, Any]The input, unchanged, from a subtype E to its supertype T
(Effect's passthroughSubtype).
Returns Getter[Any, Any]
def passthrough_subtype() -> Getter[Any, Any]:
"""The input, unchanged, from a subtype ``E`` to its supertype ``T``
(Effect's ``passthroughSubtype``)."""
return PASSTHROUGHpassthrough_supertype#
passthrough_supertype() -> Getter[Any, Any]The input, unchanged, from a supertype E to its subtype T
(Effect's passthroughSupertype). Python cannot say that T is a
subtype of E, so it is typed Any: name the types where it is used.
Returns Getter[Any, Any]
def passthrough_supertype() -> Getter[Any, Any]:
"""The input, unchanged, from a supertype ``E`` to its subtype ``T``
(Effect's ``passthroughSupertype``). Python cannot say that ``T`` is a
subtype of ``E``, so it is typed ``Any``: name the types where it is used."""
return PASSTHROUGHrequired#
required[T](**annotations) -> Getter[T, T]A missing value is a MissingKey with the key annotations
(Effect's required).
| Parameter | Type | Description |
|---|---|---|
annotations | object = {} |
Returns Getter[T, T]
def required[T](**annotations: object) -> Getter[T, T]:
"""A missing value is a ``MissingKey`` with the key ``annotations``
(Effect's ``required``)."""
def run(input: Option[T], options: ParseOptions) -> Exit[Option[T], Issue]:
return fail_exit(MissingKey(annotations or None)) if input is None else Success(input)
return TransformOptionalEffect(run)succeed#
succeed[T](value) -> Getter[T, object]Always value, present or not (Effect's succeed).
| Parameter | Type | Description |
|---|---|---|
value | T |
Returns Getter[T, object]
def succeed[T](value: T, /) -> Getter[T, object]:
"""Always ``value``, present or not (Effect's ``succeed``)."""
return TransformOptional(lambda _: Some(value))transform#
transform[T, E](f) -> Getter[T, E]f of a present value (Effect's transform).
| Parameter | Type | Description |
|---|---|---|
f | Callable[[E], T] |
Returns Getter[T, E]
def transform[T, E](f: Callable[[E], T], /) -> Getter[T, E]:
"""``f`` of a present value (Effect's ``transform``)."""
return Transform(f)transform_effect#
transform_effect[T, E, R = Never](f) -> Getter[T, E, R]f(value, options) of a present value: an effect failing with an
Issue (or an Exit), maybe needing services (Effect's
transformEffect).
| Parameter | Type | Description |
|---|---|---|
f | Callable[[E, ParseOptions], Outcome[T, R]] |
Returns Getter[T, E, R]
def transform_effect[T, E, R = Never](
f: Callable[[E, ParseOptions], Outcome[T, R]], /
) -> Getter[T, E, R]:
"""``f(value, options)`` of a present value: an effect failing with an
``Issue`` (or an ``Exit``), maybe needing services (Effect's
``transformEffect``)."""
return TransformEffect(f)transform_optional#
transform_optional[T, E](f) -> Getter[T, E]f of the input as an Option: it may supply a missing value
or omit a present one (Effect's transformOptional).
| Parameter | Type | Description |
|---|---|---|
f | Callable[[Option[E]], Option[T]] |
Returns Getter[T, E]
def transform_optional[T, E](f: Callable[[Option[E]], Option[T]], /) -> Getter[T, E]:
"""``f`` of the input as an ``Option``: it may supply a missing value
or omit a present one (Effect's ``transformOptional``)."""
return TransformOptional(f)transform_optional_effect#
transform_optional_effect[T, E, R = Never](f) -> Getter[T, E, R]f(option, options), the effectful transform_optional.
| Parameter | Type | Description |
|---|---|---|
f | Callable[[Option[E], ParseOptions], Outcome[Option[T], R]] |
Returns Getter[T, E, R]
def transform_optional_effect[T, E, R = Never](
f: Callable[[Option[E], ParseOptions], Outcome[Option[T], R]], /
) -> Getter[T, E, R]:
"""``f(option, options)``, the effectful ``transform_optional``."""
return TransformOptionalEffect(f)with_default#
with_default[T, R = Never](default) -> Getter[T, T, R]A missing value is the outcome of default (Effect's
withDefault; Python has no undefined, so only a missing value
is replaced).
| Parameter | Type | Description |
|---|---|---|
default | Outcome[T, R] |
Returns Getter[T, T, R]
def with_default[T, R = Never](default: Outcome[T, R], /) -> Getter[T, T, R]:
"""A missing value is the outcome of ``default`` (Effect's
``withDefault``; Python has no ``undefined``, so only a missing value
is replaced)."""
def run(input: Option[T], options: ParseOptions) -> Outcome[Option[T], R]:
if input is not None:
return Success(input)
if isinstance(default, Success):
return Success(Some(default.value))
if isinstance(default, Failure):
return default
return default.map(Some)
return TransformOptionalEffect(run)camel_to_snake#
camel_to_snake() -> Getter[str, str]Returns Getter[str, str]
def camel_to_snake() -> Getter[str, str]:
return Transform(camel_to_snake_text)capitalize#
capitalize() -> Getter[str, str]Returns Getter[str, str]
def capitalize() -> Getter[str, str]:
return Transform(capitalize_text)decode_uri_component#
decode_uri_component() -> Getter[str, str]JavaScript's decodeURIComponent; a malformed escape is an
InvalidValue (Effect's decodeUriComponent).
Returns Getter[str, str]
def decode_uri_component() -> Getter[str, str]:
"""JavaScript's ``decodeURIComponent``; a malformed escape is an
``InvalidValue`` (Effect's ``decodeUriComponent``)."""
def run(text: str, options: ParseOptions) -> Exit[str, Issue]:
if not _BAD_ESCAPE.search(text):
try:
return Success(unquote(text, errors="strict"))
except UnicodeDecodeError:
pass
expected = {"expected": "a valid URI component"}
return fail_exit(InvalidValue(expected, reported(text, options)))
return TransformEffect(run)encode_uri_component#
encode_uri_component() -> Getter[str, str]JavaScript's encodeURIComponent (Effect's encodeUriComponent);
a lone surrogate raises, a defect.
Returns Getter[str, str]
def encode_uri_component() -> Getter[str, str]:
"""JavaScript's ``encodeURIComponent`` (Effect's ``encodeUriComponent``);
a lone surrogate raises, a defect."""
return Transform(lambda text: quote(text, safe=_URI_SAFE))join_key_value#
join_key_value(*, separator=',', key_value_separator='=') -> Getter[str, Mapping[str, str]]The inverse of split_key_value (Effect's joinKeyValue).
| Parameter | Type | Description |
|---|---|---|
separator | str = ',' | |
key_value_separator | str = '=' |
Returns Getter[str, Mapping[str, str]]
def join_key_value(
*, separator: str = ",", key_value_separator: str = "="
) -> Getter[str, Mapping[str, str]]:
"""The inverse of ``split_key_value`` (Effect's ``joinKeyValue``)."""
return Transform(
lambda pairs: separator.join(f"{k}{key_value_separator}{v}" for k, v in pairs.items())
)snake_to_camel#
snake_to_camel() -> Getter[str, str]Returns Getter[str, str]
def snake_to_camel() -> Getter[str, str]:
return Transform(snake_to_camel_text)split#
split(*, separator=',') -> Getter[Sequence[str], str]The parts between separators; "" has none (Effect's split).
| Parameter | Type | Description |
|---|---|---|
separator | str = ',' |
Returns Getter[Sequence[str], str]
def split(*, separator: str = ",") -> Getter[Sequence[str], str]:
"""The parts between ``separator``s; ``""`` has none (Effect's ``split``)."""
return Transform(lambda text: () if text == "" else tuple(text.split(separator)))split_key_value#
split_key_value(*, separator=',', key_value_separator='=', trim=False, keep_empty_values=False) -> Getter[dict[str, str], str]"a=1,b=2" as {"a": "1", "b": "2"} (Effect's splitKeyValue): a pair
without key_value_separator or with an empty key is skipped, and one with an empty
value unless keep_empty_values (then its value is ""); trim trims keys and
values first. An empty key_value_separator takes a pair's first two characters.
| Parameter | Type | Description |
|---|---|---|
separator | str = ',' | |
key_value_separator | str = '=' | |
trim | bool = False | |
keep_empty_values | bool = False |
Returns Getter[dict[str, str], str]
def split_key_value(
*,
separator: str = ",",
key_value_separator: str = "=",
trim: bool = False,
keep_empty_values: bool = False,
) -> Getter[dict[str, str], str]:
"""``"a=1,b=2"`` as ``{"a": "1", "b": "2"}`` (Effect's ``splitKeyValue``): a pair
without ``key_value_separator`` or with an empty key is skipped, and one with an empty
value unless ``keep_empty_values`` (then its value is ``""``); ``trim`` trims keys and
values first. An empty ``key_value_separator`` takes a pair's first two characters."""
def run(text: str) -> dict[str, str]:
out: dict[str, str] = {}
for pair in text.split(separator):
if key_value_separator == "":
key, value = pair[:1], pair[1:2]
else:
index = pair.find(key_value_separator)
if index == -1:
continue
key, value = pair[:index], pair[index + len(key_value_separator) :]
if trim:
key, value = js_trim(key), js_trim(value)
if key == "" or (value == "" and not keep_empty_values):
continue
out[key] = value
return out
return Transform(run)to_lower_case#
to_lower_case() -> Getter[str, str]Returns Getter[str, str]
def to_lower_case() -> Getter[str, str]:
return Transform(str.lower)to_upper_case#
to_upper_case() -> Getter[str, str]Returns Getter[str, str]
def to_upper_case() -> Getter[str, str]:
return Transform(str.upper)trim#
trim() -> Getter[str, str]Whitespace removed from both ends, as JavaScript's trim.
Returns Getter[str, str]
def trim() -> Getter[str, str]:
"""Whitespace removed from both ends, as JavaScript's ``trim``."""
return Transform(js_trim)uncapitalize#
uncapitalize() -> Getter[str, str]Returns Getter[str, str]
def uncapitalize() -> Getter[str, str]:
return Transform(uncapitalize_text)collect_bracket_path_entries#
collect_bracket_path_entries[A](is_leaf) -> Callable[[Mapping[str, object]], list[tuple[str, A]]]A tree flattened to bracket-path entries (Effect's
collectBracketPathEntries): a list of leaves repeats its key, any
other list indexes key[i], a mapping key[k]; values that are
neither leaves nor containers are dropped.
| Parameter | Type | Description |
|---|---|---|
is_leaf | Callable[[object], TypeIs[A]] |
Returns Callable[[Mapping[str, object]], list[tuple[str, A]]]
def collect_bracket_path_entries[A](
is_leaf: Callable[[object], TypeIs[A]], /
) -> Callable[[Mapping[str, object]], list[tuple[str, A]]]:
"""A tree flattened to bracket-path entries (Effect's
``collectBracketPathEntries``): a list of leaves repeats its key, any
other list indexes ``key[i]``, a mapping ``key[k]``; values that are
neither leaves nor containers are dropped."""
def collect(tree: Mapping[str, object]) -> list[tuple[str, A]]:
entries: list[tuple[str, A]] = []
for key, value in tree.items():
_append_bracket_entries(is_leaf, entries, key, value)
return entries
return collectmake_tree_record#
make_tree_record[A](entries) -> dict[str, TreeValue[A | None]]The tree of bracket-path entries (Effect's makeTreeRecord).
| Parameter | Type | Description |
|---|---|---|
entries | Iterable[tuple[str, A]] |
Returns dict[str, TreeValue[A | None]]
def make_tree_record[A](entries: Iterable[tuple[str, A]], /) -> dict[str, TreeValue[A | None]]:
"""The tree of bracket-path ``entries`` (Effect's ``makeTreeRecord``)."""
builder = _Builder()
for path, value in entries:
builder.add(path, value)
return cast("dict[str, TreeValue[A | None]]", builder.finish())On This Page
ValuesTypesClassesFunctionsdecode_base64decode_base64_stringdecode_base64_urldecode_base64_url_stringdecode_hexdecode_hex_stringencode_base64encode_base64_urlencode_hexbig_intbooleandate_time_utc_from_inputnumberparse_jsonstringstringify_jsonruncheck_effectfailforbiddenomitpassthroughpassthrough_subtypepassthrough_supertyperequiredsucceedtransformtransform_effecttransform_optionaltransform_optional_effectwith_defaultcamel_to_snakecapitalizedecode_uri_componentencode_uri_componentjoin_key_valuesnake_to_camelsplitsplit_key_valueto_lower_caseto_upper_casetrimuncapitalizecollect_bracket_path_entriesmake_tree_record