GitHub

API reference for Iso.

class Iso[S, A]

A lossless conversion both ways (Effect's Iso): both a Lens and a Prism.

Functions

__init__

__init__(steps, get, set)
ParameterTypeDescription
stepstuple[Step, ...]
getCallable[[S], A]
setCallable[[A], S]
def __init__(self, steps: tuple[Step, ...], get: Callable[[S], A], set: Callable[[A], S]):
    def get_result(s: S) -> Result[A, Issue]:
        return Ok(get(s))

    def replace(a: A, _: S) -> S:
        return set(a)

    # Prism's constructor (next after Lens in the MRO) sets the rest.
    super(Lens, self).__init__(steps, get_result, set)
    self._get = get
    self._replace = replace

replace

replace(a, s) -> S
ParameterTypeDescription
aA
sS

Returns S

def replace(self, a: A, s: S, /) -> S:
    return self._set(a)

modify

modify(f) -> Callable[[S], S]
ParameterTypeDescription
fCallable[[A], A]

Returns Callable[[S], S]

def modify(self, f: Callable[[A], A], /) -> Callable[[S], S]:
    return lambda s: self._set(f(self._get(s)))

get_result

get_result(s) -> Result[A, Issue]

The focus of s, or the issue saying why there is none.

ParameterTypeDescription
sS

Returns Result[A, Issue]

def get_result(self, s: S, /) -> Result[A, Issue]:
    """The focus of ``s``, or the issue saying why there is none."""
    return self._get_result(s)

replace_result

replace_result(a, s) -> Result[S, Issue]

s with a in place of its focus, or why it cannot be.

ParameterTypeDescription
aA
sS

Returns Result[S, Issue]

def replace_result(self, a: A, s: S, /) -> Result[S, Issue]:
    """``s`` with ``a`` in place of its focus, or why it cannot be."""
    return self._replace_result(a, s)

compose

compose[B](that: Iso[A, B], /) -> Iso[S, B]
compose[B](that: Lens[A, B], /) -> Lens[S, B]
compose[B](that: Prism[A, B], /) -> Prism[S, B]
compose[B](that: Optional[A, B], /) -> Optional[S, B]

This optic, then that on its focus; the kind is the weaker.

ParameterTypeDescription
that
@overload
def compose[B](self: Iso[S, A], that: Iso[A, B], /) -> Iso[S, B]: ...
@overload
def compose[B](self: Lens[S, A], that: Lens[A, B], /) -> Lens[S, B]: ...
@overload
def compose[B](self: Prism[S, A], that: Prism[A, B], /) -> Prism[S, B]: ...
@overload
def compose[B](self: Optional[S, A], that: Optional[A, B], /) -> Optional[S, B]: ...
def compose(self, that: Optional[Any, Any], /) -> Any:
    """This optic, then ``that`` on its focus; the kind is the weaker."""
    return make(compose_steps(self._steps, that._steps))

key

key(key: Hashable, /) -> Lens[S, Any]
key(key: Hashable, /) -> Optional[S, Any]

The value at key: a dict key, a list or tuple index, or an attribute of a dataclass. A missing one reads as None.

ParameterTypeDescription
key
@overload
def key(self: Lens[S, A], key: Hashable, /) -> Lens[S, Any]: ...
@overload
def key(self: Optional[S, A], key: Hashable, /) -> Optional[S, Any]: ...
def key(self, key: Hashable, /) -> Any:
    """The value at ``key``: a dict key, a list or tuple index, or an
    attribute of a dataclass. A missing one reads as ``None``."""
    return self._then((path_step((key,)),))

optional_key

optional_key(key: Hashable, /) -> Lens[S, Any]
optional_key(key: Hashable, /) -> Optional[S, Any]

The value at key, None when missing; writing None removes the key (an element is removed, later ones move down).

ParameterTypeDescription
key
@overload
def optional_key(self: Lens[S, A], key: Hashable, /) -> Lens[S, Any]: ...
@overload
def optional_key(self: Optional[S, A], key: Hashable, /) -> Optional[S, Any]: ...
def optional_key(self, key: Hashable, /) -> Any:
    """The value at ``key``, ``None`` when missing; writing ``None``
    removes the key (an element is removed, later ones move down)."""

    def replace(a: object, s: object) -> object:
        return _data.remove(s, key) if a is None else _data.assign(s, key, a)

    return self._then((Step("Lens", lambda s: _data.get(s, key), replace),))

check

check(*checks: ast.Check[A] = ()) -> Prism[S, A]
check(*checks: ast.Check[A] = ()) -> Optional[S, A]

Only a focus every check accepts; the issue holds each failure.

ParameterTypeDescription
checks= ()
@overload
def check(self: Prism[S, A], *checks: ast.Check[A]) -> Prism[S, A]: ...
@overload
def check(self: Optional[S, A], *checks: ast.Check[A]) -> Optional[S, A]: ...
def check(self, *checks: ast.Check[Any]) -> Any:
    """Only a focus every check accepts; the issue holds each failure."""
    first, *rest = checks
    return self._then((checks_step((first, *rest)),))

refine

refine[B](guard: Callable[[A], TypeIs[B]], /, **annotations: object = {}) -> Prism[S, B]
refine[B](guard: Callable[[A], TypeIs[B]], /, **annotations: object = {}) -> Optional[S, B]

Only a focus guard accepts, narrowed to its type; the issue is Expected <expected> (the expected annotation).

ParameterTypeDescription
guard
annotations= {}
@overload
def refine[B](
    self: Prism[S, A], guard: Callable[[A], TypeIs[B]], /, **annotations: object
) -> Prism[S, B]: ...
@overload
def refine[B](
    self: Optional[S, A], guard: Callable[[A], TypeIs[B]], /, **annotations: object
) -> Optional[S, B]: ...
def refine(self, guard: Callable[[Any], bool], /, **annotations: object) -> Any:
    """Only a focus ``guard`` accepts, narrowed to its type; the issue is
    ``Expected <expected>`` (the ``expected`` annotation)."""
    return self._then((checks_step((ast.make_filter_by_guard(guard, annotations or None),)),))

tag

tag(tag: ast.LiteralValue, /) -> Prism[S, A]
tag(tag: ast.LiteralValue, /) -> Optional[S, A]

Only a focus whose _tag (a key or an attribute) is tag.

ParameterTypeDescription
tag
@overload
def tag(self: Prism[S, A], tag: ast.LiteralValue, /) -> Prism[S, A]: ...
@overload
def tag(self: Optional[S, A], tag: ast.LiteralValue, /) -> Optional[S, A]: ...
def tag(self, tag: ast.LiteralValue, /) -> Any:
    """Only a focus whose ``_tag`` (a key or an attribute) is ``tag``."""
    issue: Err[Issue] = Err(InvalidValue({"expected": f"{_json_text.stringify(tag)} tag"}))

    def get(s: object) -> Result[object, Issue]:
        found = _data.get(s, "_tag") if _data.has(s, "_tag") else None
        return Ok(s) if found == tag else issue

    return self._then((Step("Prism", get, same),))

at

at(key) -> Optional[S, Any]

The value at key when s has it: a missing key is an issue (MissingKey at key), and writing needs the key there.

ParameterTypeDescription
keyHashable

Returns Optional[S, Any]

def at(self, key: Hashable, /) -> Optional[S, Any]:
    """The value at ``key`` when ``s`` has it: a missing key is an issue
    (``MissingKey`` at ``key``), and writing needs the key there."""
    missing: Err[Issue] = Err(Pointer((key,), MissingKey()))

    def get(s: object) -> Result[object, Issue]:
        return Ok(_data.get(s, key)) if _data.has(s, key) else missing

    def replace(a: object, s: object) -> Result[object, Issue]:
        return Ok(_data.assign(s, key, a)) if _data.has(s, key) else missing

    return self._then((Step("Optional", get, replace),))

pick

pick(*keys: Hashable = ()) -> Lens[S, dict[Any, Any]]
pick(*keys: Hashable = ()) -> Optional[S, dict[Any, Any]]

A dict of the keys the focus has; writing it replaces those keys (one left out of the replacement is deleted).

ParameterTypeDescription
keys= ()
@overload
def pick(self: Lens[S, A], *keys: Hashable) -> Lens[S, dict[Any, Any]]: ...
@overload
def pick(self: Optional[S, A], *keys: Hashable) -> Optional[S, dict[Any, Any]]: ...
def pick(self, *keys: Hashable) -> Any:
    """A dict of the ``keys`` the focus has; writing it replaces those
    keys (one left out of the replacement is deleted)."""
    return self._then((Step("Lens", _picker(keys, True), _merger(keys, True)),))

omit

omit(*keys: Hashable = ()) -> Lens[S, dict[Any, Any]]
omit(*keys: Hashable = ()) -> Optional[S, dict[Any, Any]]

A dict of the focus without keys; writing it replaces every other key.

ParameterTypeDescription
keys= ()
@overload
def omit(self: Lens[S, A], *keys: Hashable) -> Lens[S, dict[Any, Any]]: ...
@overload
def omit(self: Optional[S, A], *keys: Hashable) -> Optional[S, dict[Any, Any]]: ...
def omit(self, *keys: Hashable) -> Any:
    """A dict of the focus without ``keys``; writing it replaces every
    other key."""
    return self._then((Step("Lens", _picker(keys, False), _merger(keys, False)),))

not_none

not_none[B]() -> Prism[S, B]
not_none[B]() -> Optional[S, B]

Only a focus that is not None (Effect's notUndefined).

@overload
def not_none[B](self: Prism[S, B | None]) -> Prism[S, B]: ...
@overload
def not_none[B](self: Optional[S, B | None]) -> Optional[S, B]: ...
def not_none(self) -> Any:
    """Only a focus that is not ``None`` (Effect's ``notUndefined``)."""
    guard = ast.make_filter_by_guard(_is_not_none, {"expected": "a value other than `None`"})
    return self._then((checks_step((guard,)),))

for_each

for_each[E, B](f: Callable[[Iso[E, E]], Optional[E, B]], /) -> Optional[S, list[B]]
for_each[E, B](f: Callable[[Iso[E, E]], Optional[E, B]], /) -> Optional[S, tuple[B, ...]]
for_each[E, B](f: Callable[[Iso[E, E]], Optional[E, B]], /) -> Optional[S, Sequence[B]]

Each element's focus under f's optic, in order (those it finds); writing takes one replacement per element found, in the same container type as the source.

ParameterTypeDescription
f
@overload
def for_each[E, B](
    self: Optional[S, list[E]], f: Callable[[Iso[E, E]], Optional[E, B]], /
) -> Optional[S, list[B]]: ...
@overload
def for_each[E, B](
    self: Optional[S, tuple[E, ...]], f: Callable[[Iso[E, E]], Optional[E, B]], /
) -> Optional[S, tuple[B, ...]]: ...
@overload
def for_each[E, B](
    self: Optional[S, Sequence[E]], f: Callable[[Iso[E, E]], Optional[E, B]], /
) -> Optional[S, Sequence[B]]: ...
def for_each(self, f: Callable[[Any], Optional[Any, Any]], /) -> Any:
    """Each element's focus under ``f``'s optic, in order (those it finds);
    writing takes one replacement per element found, in the same
    container type as the source."""
    inner = f(Id[Any]())
    this = cast("Optional[Any, Sequence[Any]]", self)

    def get(s: object) -> Result[Sequence[Any], Issue]:
        got = this.get_result(s)
        if isinstance(got, Err):
            return got
        found = [r.value for r in map(inner.get_result, got.value) if isinstance(r, Ok)]
        return Ok(_like(got.value, found))

    def replace(bs: Sequence[Any], s: object) -> Result[object, Issue]:
        got = this.get_result(s)
        if isinstance(got, Err):
            return got
        items = got.value
        indexes = [i for i, a in enumerate(items) if isinstance(inner.get_result(a), Ok)]
        if len(bs) != len(indexes):
            message = f"each: replacement length mismatch: {len(bs)} !== {len(indexes)}"
            return Err(InvalidValue({"message": message}))
        out = list(items)
        for i, b in zip(indexes, bs, strict=True):
            replaced = inner.replace_result(b, items[i])
            if isinstance(replaced, Err):
                return Err(Pointer((i,), replaced.error))
            out[i] = replaced.value
        return this.replace_result(_like(items, out), s)

    return make_optional(get, replace)

modify_all

modify_all[E](f: Callable[[E], E], /) -> Callable[[S], S]
modify_all[E](f: Callable[[E], E], /) -> Callable[[S], S]
modify_all[E](f: Callable[[E], E], /) -> Callable[[S], S]

A function applying f to every focused element; it gives the source back when the traversal fails.

ParameterTypeDescription
f
@overload
def modify_all[E](self: Optional[S, list[E]], f: Callable[[E], E], /) -> Callable[[S], S]: ...
@overload
def modify_all[E](
    self: Optional[S, tuple[E, ...]], f: Callable[[E], E], /
) -> Callable[[S], S]: ...
@overload
def modify_all[E](
    self: Optional[S, Sequence[E]], f: Callable[[E], E], /
) -> Callable[[S], S]: ...
def modify_all(self, f: Callable[[Any], Any], /) -> Callable[[S], S]:
    """A function applying ``f`` to every focused element; it gives the
    source back when the traversal fails."""
    this = cast("Optional[S, Sequence[Any]]", self)

    def modify(s: S) -> S:
        got = this.get_result(s)
        if isinstance(got, Err):
            return s
        return this.replace(_like(got.value, [f(a) for a in got.value]), s)

    return modify

get_all

get_all[E](s: S, /) -> list[E]
get_all[E](s: S, /) -> list[E]
get_all[E](s: S, /) -> list[E]

Every focused element, or none when the traversal fails.

ParameterTypeDescription
s
@overload
def get_all[E](self: Optional[S, list[E]], s: S, /) -> list[E]: ...
@overload
def get_all[E](self: Optional[S, tuple[E, ...]], s: S, /) -> list[E]: ...
@overload
def get_all[E](self: Optional[S, Sequence[E]], s: S, /) -> list[E]: ...
def get_all(self, s: S, /) -> list[Any]:
    """Every focused element, or none when the traversal fails."""
    got = cast("Optional[S, Sequence[Any]]", self).get_result(s)
    return list(got.value) if isinstance(got, Ok) else []

set

set(a) -> S

The whole S made from a.

ParameterTypeDescription
aA

Returns S

def set(self, a: A, /) -> S:
    """The whole ``S`` made from ``a``."""
    return self._set(a)

get

get(s) -> A

The focus of s.

ParameterTypeDescription
sS

Returns A

def get(self, s: S, /) -> A:
    """The focus of ``s``."""
    return self._get(s)