GitHub

API reference for schema.

Schemas (Effect's Schema): describe a value once, then decode, validate and encode it::

from pyfect import schema as S

S.decode_unknown_sync(S.String)("a")    # "a"
S.decode_unknown_sync(S.String)(1)      # raises SchemaError("Expected string")
S.decode_unknown_result(S.Number)("a")  # Err(SchemaError(...))

A schema is a Bottom[T, E, RD, RE]: it decodes an E (Encoded) into a T (Type) and encodes back, needing services RD / RE. Anything that takes a schema accepts a Codec[T, E, RD, RE]; Schema[T], Decoder[T] and Encoder[E] leave the other parameters open.

The decoders and encoders (decode_unknown_sync, encode_effect, ...) take parse options as keyword arguments (errors="all", report_input=True, see ParseOptions) both when made and when called. They fail with SchemaError, whose issue (pyfect.schema.issue) says what was wrong and where; the AST is in pyfect.schema.ast.

to_codec_json(schema) reads and writes the schema's values as JSON (non-finite numbers as text, bigints as digits, Option as a tagged object, ...), to_codec_string_tree(schema) as a tree of strings; to_json_schema_document(schema) is the JSON Schema of that JSON form. to_equivalence(schema) compares two decoded values and to_formatter(schema) writes one as text (some(1), { "a": 1 }); override_to_equivalence / override_to_formatter replace a schema's.

See docs/SCHEMA_DESIGN.md for how schemas are typed.

Re-exports

Values

AttributeTypeDescription
BooleanLiteralsDecodeToSchema[bool, str]

A bool read from one of those texts, written as "true" / "false".

FalseLiteralsLiteralsSchema[FalseLiteral]
TrueLiteralsLiteralsSchema[TrueLiteral]
is_betweenBetween[float]
is_between_big_intBetween[int]
is_between_dateBetween[datetime]
is_greater_thanBound[float]
is_greater_than_big_intBound[int]
is_greater_than_dateBound[datetime]
is_greater_than_or_equal_toBound[float]
is_greater_than_or_equal_to_big_intBound[int]
is_greater_than_or_equal_to_dateBound[datetime]
is_less_thanBound[float]
is_less_than_big_intBound[int]
is_less_than_dateBound[datetime]
is_less_than_or_equal_toBound[float]
is_less_than_or_equal_to_big_intBound[int]
is_less_than_or_equal_to_dateBound[datetime]
URLBottom[Url]

A parsed URL, a Url (Effect's URL), whose str() is its href.

BigIntFromStringDecodeToSchema[int, str]
BooleanFromBitDecodeToSchema[bool, int]

0 / 1 as False / True.

BytesBottom[bytes]

bytes (Effect's Uint8Array).

BytesFromBase64DecodeToSchema[bytes, str]

Bytes from Base64 text (Effect's Uint8ArrayFromBase64).

BytesFromBase64UrlDecodeToSchema[bytes, str]
BytesFromHexDecodeToSchema[bytes, str]
ByteSizeFromBigIntDecodeToSchema[_ByteSize, int]
ByteSizeFromNumberDecodeToSchema[_ByteSize, float]
ByteSizeFromStringDecodeToSchema[_ByteSize, str]
DateTimeUtcFromDateDecodeToSchema[datetime, datetime]

A UTC datetime from an aware datetime in any zone (Effect's DateTimeUtcFromDate, a JavaScript Date being an instant); encodes as the UTC datetime. A naive datetime is rejected.

DateTimeUtcFromMillisDecodeToSchema[datetime, int]

A UTC datetime from epoch milliseconds.

DateTimeUtcFromStringDecodeToSchema[datetime, str]

A UTC datetime from ISO 8601 (or RFC 2822) text; encodes as DateTime.formatIso (milliseconds, Z).

DateTimeZonedFromStringDecodeToSchema[datetime, str]
FiniteFromStringDecodeToSchema[float, str]
NumberFromStringDecodeToSchema[float, str]

A number from its text, as JavaScript's Number reads it (NaN for what is not a number).

StringFromBase64DecodeToSchema[str, str]
StringFromBase64UrlDecodeToSchema[str, str]
StringFromHexDecodeToSchema[str, str]
StringFromUriComponentDecodeToSchema[str, str]
TimeZoneFromStringDecodeToSchema[tzinfo, str]
TimeZoneNamedFromStringDecodeToSchema[ZoneInfo, str]
TrimDecodeToSchema[str, str]

A string, trimmed when decoding.

UnknownFromJsonStringDecodeToSchema[object, str]

Any JSON value, from its text.

URLFromStringDecodeToSchema[Url, str]
BigDecimalBottom[bd.BigDecimal]

A big_decimal.BigDecimal (Effect's BigDecimal).

BigDecimalFromStringDecodeToSchema[bd.BigDecimal, str]

A BigDecimal read from its text (Effect's BigDecimalFromString).

RegExpBottom[re.Pattern[str]]

A compiled re.Pattern[str] (Effect's RegExp).

is_between_big_decimalBetween[bd.BigDecimal]
is_greater_than_big_decimalBound[bd.BigDecimal]
is_greater_than_or_equal_to_big_decimalBound[bd.BigDecimal]
is_less_than_big_decimalBound[bd.BigDecimal]
is_less_than_or_equal_to_big_decimalBound[bd.BigDecimal]
DurationFromIsoStringDecodeToSchema[_duration.Duration, str]

A Duration read from an ISO 8601 duration ("PT1H30M"); years and months are rejected.

DurationFromMillisDecodeToSchema[_duration.Duration, float]

A Duration read from a count of milliseconds.

DurationFromNanosDecodeToSchema[_duration.Duration, int]

A Duration read from a count of nanoseconds.

DurationFromStringDecodeToSchema[_duration.Duration, str]

A Duration read from Effect's Duration text ("5 seconds").

DnsAaaaRecordBottom[Aaaa, Aaaa, Never, Never]
DnsARecordBottom[A, A, Never, Never]
DnsCaaRecordBottom[Caa, Caa, Never, Never]
DnsCnameRecordBottom[Cname, Cname, Never, Never]
DnsMxRecordBottom[Mx, Mx, Never, Never]
DnsNaptrRecordBottom[Naptr, Naptr, Never, Never]
DnsNsRecordBottom[Ns, Ns, Never, Never]
DnsPtrRecordBottom[Ptr, Ptr, Never, Never]
DnsRecordBottom[dns.DnsRecord]

Any DNS record (pyfect.net.dns).

DnsRecordTypeLiteralsSchema[dns.RecordType]

A DNS record type ("A", "MX", ...).

DnsSoaRecordBottom[Soa, Soa, Never, Never]
DnsSrvRecordBottom[Srv, Srv, Never, Never]
DnsTlsaRecordBottom[Tlsa, Tlsa, Never, Never]
DnsTxtRecordBottom[Txt, Txt, Never, Never]
DomainNameBottom[DomainName, str, Never, Never]

A normalized host.DomainName.

DomainNameFromStringDecodeToSchema[DomainName, str, Never, Never]
HostBottom[host.Host, Any]

An IP address, a scoped IPv6 literal or a domain name.

HostFromStringBottom[host.Host, str]
HostPortBottom[host.HostPort]
HostPortFromStringDecodeToSchema[HostPort, str, Never, Never]
InetAddressBottom[na.InetAddress]
InetAddressFromStringDecodeToSchema[InetAddressV4 | InetAddressV6, str, Never, Never]
InetAddressV4Bottom[na.InetAddressV4]
InetAddressV6Bottom[na.InetAddressV6]
IpAddressBottom[na.IpAddress]

An IPv4 or IPv6 address.

IpAddressFromStringDecodeToSchema[IPv4Address | IPv6Address, str, Never, Never]
IpInterfaceBottom[ip_interface.IpInterface]
IpInterfaceFromStringDecodeToSchema[IPv4Interface | IPv6Interface, str, Never, Never]
IpLinkLocalAddressBottom[IPv4Address | IPv6Address, IPv4Address | IPv6Address, Never, Never]
IpLinkLocalAddressFromStringBottom[IPv4Address | IPv6Address, str, Never, Never]
IpLoopbackAddressBottom[IPv4Address | IPv6Address, IPv4Address | IPv6Address, Never, Never]
IpLoopbackAddressFromStringBottom[IPv4Address | IPv6Address, str, Never, Never]
IpMulticastAddressBottom[IPv4Address | IPv6Address, IPv4Address | IPv6Address, Never, Never]
IpMulticastAddressFromStringBottom[IPv4Address | IPv6Address, str, Never, Never]
IpNetworkBottom[ip_network.IpNetwork]
IpNetworkFromStringDecodeToSchema[IPv4Network | IPv6Network, str, Never, Never]
IpUnicastAddressBottom[IPv4Address | IPv6Address, IPv4Address | IPv6Address, Never, Never]
IpUnicastAddressFromStringBottom[IPv4Address | IPv6Address, str, Never, Never]
IpUnspecifiedAddressBottom[IPv4Address | IPv6Address, IPv4Address | IPv6Address, Never, Never]
IpUnspecifiedAddressFromStringBottom[IPv4Address | IPv6Address, str, Never, Never]
Ipv4AddressBottom[IPv4Address]

An ipaddress.IPv4Address.

Ipv4AddressFromStringDecodeToSchema[IPv4Address, str, Never, Never]
Ipv4BroadcastAddressBottom[IPv4Address, IPv4Address, Never, Never]
Ipv4BroadcastAddressFromStringBottom[IPv4Address, str, Never, Never]
Ipv4InterfaceBottom[IPv4Interface]
Ipv4InterfaceFromStringDecodeToSchema[IPv4Interface, str, Never, Never]
Ipv4NetworkBottom[IPv4Network]
Ipv4NetworkFromStringDecodeToSchema[IPv4Network, str, Never, Never]
Ipv4PrivateAddressBottom[IPv4Address, IPv4Address, Never, Never]
Ipv4PrivateAddressFromStringBottom[IPv4Address, str, Never, Never]
Ipv6AddressBottom[IPv6Address]

An ipaddress.IPv6Address.

Ipv6AddressFromStringDecodeToSchema[IPv6Address, str, Never, Never]
Ipv6InterfaceBottom[IPv6Interface]
Ipv6InterfaceFromStringDecodeToSchema[IPv6Interface, str, Never, Never]
Ipv6NetworkBottom[IPv6Network]
Ipv6NetworkFromStringDecodeToSchema[IPv6Network, str, Never, Never]
Ipv6UniqueLocalAddressBottom[IPv6Address, IPv6Address, Never, Never]
Ipv6UniqueLocalAddressFromStringBottom[IPv6Address, str, Never, Never]
MacAddressBottom[na.MacAddress]

A net_address.MacAddress.

MacAddressFromStringDecodeToSchema[MacAddress, str, Never, Never]
MacBroadcastAddressBottom[MacAddress, MacAddress, Never, Never]
MacBroadcastAddressFromStringBottom[MacAddress, str, Never, Never]
MacLocallyAdministeredAddressBottom[MacAddress, MacAddress, Never, Never]
MacLocallyAdministeredAddressFromStringBottom[MacAddress, str, Never, Never]
MacMulticastAddressBottom[MacAddress, MacAddress, Never, Never]
MacMulticastAddressFromStringBottom[MacAddress, str, Never, Never]
MacUnicastAddressBottom[MacAddress, MacAddress, Never, Never]
MacUnicastAddressFromStringBottom[MacAddress, str, Never, Never]
MacUniversallyAdministeredAddressBottom[MacAddress, MacAddress, Never, Never]
MacUniversallyAdministeredAddressFromStringBottom[MacAddress, str, Never, Never]
ScopedIpv6LiteralBottom[ScopedIpv6Literal, str, Never, Never]

A canonical net_address.ScopedIpv6Literal (address%zone).

ScopedIpv6LiteralFromStringDecodeToSchema[ScopedIpv6Literal, str, Never, Never]
SocketAddressBottom[na.SocketAddress]
UnixPathAddressBottom[na.UnixPathAddress]
UnixPathAddressFromStringDecodeToSchema[na.UnixPathAddress, str]
AnyBottom[_Any]

Accepts anything, typed Any.

BigIntBottom[int]

An int (not a bool): Effect's bigint, which Python's int is.

BooleanBottom[bool]
CharBottom[str]

A string of one character.

FiniteBottom[float]

A number that is not NaN nor an infinity.

IntBottom[int]

An int (not a bool): Effect's Int, with its messages (Expected number, then Expected an integer). 1.0 is taken, as 1.

NaturalBottom[int]

An int from 0.

NeverBottom[_Never]

Accepts nothing.

NonEmptyStringBottom[str]
NullBottom[None]

None.

NumberBottom[float]

An int or float (not a bool): JavaScript's number.

PortBottom[int]

An int from 0 to 65535.

StringBottom[str]
TrimmedBottom[str]

A string with no leading or trailing whitespace.

UnknownBottom[object]

Accepts anything, typed object.

SemVerBottom[semver.SemVer]

A semver.SemVer (Effect's SemVer).

SemVerFromStringDecodeToSchema[semver.SemVer, str]
SemVerRangeBottom[semver_range.SemVerRange]

A semver_range.SemVerRange (Effect's SemVerRange).

SemVerRangeFromStringDecodeToSchema[semver_range.SemVerRange, str]
StandardSchemaV1FailureResultBottom[FailureResult, FailureResult, Never, Never]

The schema of a Standard Schema failure result: issues, each a message and an optional path of keys (numbers or strings) or {"key": ...} segments (Effect's Schema.StandardSchemaV1FailureResult).

ByteSizeBottom[_ByteSize]

A byte_size.ByteSize: a non-negative int (Effect's ByteSize).

DateTimeUtcBottom[datetime]

An aware datetime in timezone.utc (Effect's DateTimeUtc).

DateTimeZonedBottom[datetime]

An aware datetime (Effect's DateTimeZoned); a naive one is rejected.

DurationBottom[DurationValue]

A Duration (Effect's Schema.Duration).

JsonBottom[JsonValue]

Any JSON value (ast.is_json), unchanged: Expected JSON value otherwise (Effect's Json).

JsonObjectRecordSchema[str, JsonValue, str, JsonValue, Never, Never]

A string-keyed mapping of JSON values (Effect's JsonObject).

TimeZoneBottom[tzinfo]

A ZoneInfo or a datetime.timezone (Effect's TimeZone).

TimeZoneNamedBottom[ZoneInfo]

A ZoneInfo (Effect's TimeZoneNamed).

TimeZoneOffsetBottom[timezone]

A fixed-offset datetime.timezone (Effect's TimeZoneOffset).

ObjectKeywordBottom[object]

Anything but a primitive; JSON holds an array or an object of JSON, a string tree those of string trees, as Effect's.

UndefinedBottom[None]
VoidBottom[None, object]

Takes anything and gives None, in both directions, as void ignores a value; JSON writes it as null.

Types

TypeDefinitionDescription
TupleElementtype TupleElement[RD = object, RE = object] = Codec[object, object, RD, RE] | OptionalKey[object, object, RD, RE]

What a tuple holds: an element's schema, or one wrapped in optional_key.

Parsetype Parse[T = object] = Callable[[object, ast.Declaration, ParseOptions], Exit[T, Issue] | Effect[T, Issue, Any]]

A declaration's parser: the input, the declaration (for its issues) and the parse options. It gives an Exit, or an Effect when a part's parse is one (ast.then / ast.map_value keep either).

DefectSchematype DefectSchema = DecodeToSchema[object, JsonValue, Never, Never]
CheckOutputtype CheckOutput = JsonSchema | tuple[JsonSchema, Literal[True]]
OnExcessPropertytype OnExcessProperty = Literal['ignore', 'error']
ReferencePolicytype ReferencePolicy = Callable[[ReferenceCandidate], str | None]

The definition key of a candidate, or None to inline it (a recursive one is then still a definition, keyed by its kind).

ToJsonSchematype ToJsonSchema = Callable[[CheckContext], CheckOutput]
LiteralValuetype LiteralValue = LiteralString | int | float | bool | None

What a literal may be: a string, a number, a boolean or None.

EncodingStrategytype EncodingStrategy = Literal['passthrough', 'omit']

What a defaulted key encodes to: its value, or nothing.

Decodertype Decoder[A, R = Never] = Codec[A, object, R, object]
Encodertype Encoder[I, R = Never] = Codec[object, I, object, R]
Schematype Schema[A] = Codec[A, object, object, object]
Toptype Top = Codec[object, object, object, object]
StringTreetype StringTree = str | Sequence[StringTree] | Mapping[str, StringTree] | None

Text leaves (None for Effect's undefined) in lists and string-keyed mappings (Effect's StringTree).

Equivalencetype Equivalence[A] = Callable[[A, A], bool]

Whether two values are the same (Effect's Equivalence).

Formattertype Formatter[A] = Callable[[A], str]

A value as text (Effect's Formatter).

OnBeforetype OnBefore = Callable[[ast.AST, Callable[[ast.AST], Formatter[Any]]], Formatter[Any] | None]

Takes a node before the derivation does: its formatter, or None to leave it to the derivation (which it may call).

Sourcetype Source[T, E, RD, RE] = Codec[T, E, RD, RE] | OptionalKey[T, E, RD, RE]

What decode_to takes as its source: a schema, or one in optional_key.

TreeValuetype TreeValue[N] = N | Sequence[TreeValue[N]] | Mapping[str, TreeValue[N]]

A node, a sequence of trees or a string-keyed mapping of trees (decoded as a tuple and a dict).

JsonValuetype JsonValue = bool | int | float | str | Sequence[JsonValue] | Mapping[str, JsonValue] | None

A JSON value (Effect's Json type): a list or tuple for an array, a string-keyed mapping for an object. pyfect.encoding.Json (what json.loads returns) is one.

Classes

Functions

Array

Array[A, I, RD, RE](value) -> ArraySchema[tuple[A, ...], A, I, RD, RE]

Any number of value's values, as a tuple (Effect's Array, a readonly array).

ParameterTypeDescription
valueCodec[A, I, RD, RE]

Returns ArraySchema[tuple[A, ...], A, I, RD, RE]

def Array[A, I, RD, RE](value: Codec[A, I, RD, RE], /) -> ArraySchema[tuple[A, ...], A, I, RD, RE]:
    """Any number of ``value``'s values, as a ``tuple`` (Effect's
    ``Array``, a readonly array)."""
    return ArraySchema(ast.Arrays((), (value.__codec__().ast,)), value)

List

List[A, I, RD, RE](value) -> ArraySchema[list[A], A, I, RD, RE]

Any number of value's values, as a list (Effect's mutable(Array(...))).

ParameterTypeDescription
valueCodec[A, I, RD, RE]

Returns ArraySchema[list[A], A, I, RD, RE]

def List[A, I, RD, RE](value: Codec[A, I, RD, RE], /) -> ArraySchema[list[A], A, I, RD, RE]:
    """Any number of ``value``'s values, as a ``list`` (Effect's
    ``mutable(Array(...))``)."""
    return ArraySchema(ast.Arrays((), (value.__codec__().ast,), mutable=True), value)

NonEmptyArray

NonEmptyArray[A, I, RD, RE](value) -> ArraySchema[tuple[A, *(tuple[A, ...])], A, I, RD, RE]

One or more of value's values, as a tuple: an empty input is Missing key at [0].

ParameterTypeDescription
valueCodec[A, I, RD, RE]

Returns ArraySchema[tuple[A, *(tuple[A, ...])], A, I, RD, RE]

def NonEmptyArray[A, I, RD, RE](
    value: Codec[A, I, RD, RE], /
) -> ArraySchema[tuple[A, *tuple[A, ...]], A, I, RD, RE]:
    """One or more of ``value``'s values, as a ``tuple``: an empty input is
    ``Missing key`` at ``[0]``."""
    node = value.__codec__().ast
    return ArraySchema(ast.Arrays((ast.Element(node),), (node,)), value)

Tuple

Tuple() -> _Tuple[tuple[], tuple[], Never, Never]
Tuple[A1, I1, RD, RE](e1: Codec[A1, I1, RD, RE], /) -> _Tuple[tuple[A1], tuple[I1], RD, RE]
Tuple[A1, I1, A2, I2, RD, RE](e1: Codec[A1, I1, RD, RE], e2: Codec[A2, I2, RD, RE], /) -> _Tuple[tuple[A1, A2], tuple[I1, I2], RD, RE]
Tuple[A1, I1, A2, I2, A3, I3, RD, RE](e1: Codec[A1, I1, RD, RE], e2: Codec[A2, I2, RD, RE], e3: Codec[A3, I3, RD, RE], /) -> _Tuple[tuple[A1, A2, A3], tuple[I1, I2, I3], RD, RE]
Tuple[A1, I1, A2, I2, A3, I3, A4, I4, RD, RE](e1: Codec[A1, I1, RD, RE], e2: Codec[A2, I2, RD, RE], e3: Codec[A3, I3, RD, RE], e4: Codec[A4, I4, RD, RE], /) -> _Tuple[tuple[A1, A2, A3, A4], tuple[I1, I2, I3, I4], RD, RE]
Tuple[A1, I1, A2, I2, A3, I3, A4, I4, A5, I5, RD, RE](e1: Codec[A1, I1, RD, RE], e2: Codec[A2, I2, RD, RE], e3: Codec[A3, I3, RD, RE], e4: Codec[A4, I4, RD, RE], e5: Codec[A5, I5, RD, RE], /) -> _Tuple[tuple[A1, A2, A3, A4, A5], tuple[I1, I2, I3, I4, I5], RD, RE]
Tuple[A1, I1, A2, I2, A3, I3, A4, I4, A5, I5, A6, I6, RD, RE](e1: Codec[A1, I1, RD, RE], e2: Codec[A2, I2, RD, RE], e3: Codec[A3, I3, RD, RE], e4: Codec[A4, I4, RD, RE], e5: Codec[A5, I5, RD, RE], e6: Codec[A6, I6, RD, RE], /) -> _Tuple[tuple[A1, A2, A3, A4, A5, A6], tuple[I1, I2, I3, I4, I5, I6], RD, RE]
Tuple[A1, I1, A2, I2, A3, I3, A4, I4, A5, I5, A6, I6, A7, I7, RD, RE](e1: Codec[A1, I1, RD, RE], e2: Codec[A2, I2, RD, RE], e3: Codec[A3, I3, RD, RE], e4: Codec[A4, I4, RD, RE], e5: Codec[A5, I5, RD, RE], e6: Codec[A6, I6, RD, RE], e7: Codec[A7, I7, RD, RE], /) -> _Tuple[tuple[A1, A2, A3, A4, A5, A6, A7], tuple[I1, I2, I3, I4, I5, I6, I7], RD, RE]
Tuple[A1, I1, A2, I2, A3, I3, A4, I4, A5, I5, A6, I6, A7, I7, A8, I8, RD, RE](e1: Codec[A1, I1, RD, RE], e2: Codec[A2, I2, RD, RE], e3: Codec[A3, I3, RD, RE], e4: Codec[A4, I4, RD, RE], e5: Codec[A5, I5, RD, RE], e6: Codec[A6, I6, RD, RE], e7: Codec[A7, I7, RD, RE], e8: Codec[A8, I8, RD, RE], /) -> _Tuple[tuple[A1, A2, A3, A4, A5, A6, A7, A8], tuple[I1, I2, I3, I4, I5, I6, I7, I8], RD, RE]
Tuple[A, I, RD, RE](*elements: Codec[A, I, RD, RE] | OptionalKey[A, I, RD, RE] = ()) -> _Tuple[tuple[A, ...], tuple[I, ...], RD, RE]

A tuple of one value per element (Effect's Tuple): a missing element is a Missing key issue, an extra position Expected no excess property.

ParameterTypeDescription
elements= ()
@overload
def Tuple() -> _Tuple[tuple[()], tuple[()], Never, Never]: ...
@overload
def Tuple[A1, I1, RD, RE](e1: Codec[A1, I1, RD, RE], /) -> _Tuple[tuple[A1], tuple[I1], RD, RE]: ...
@overload
def Tuple[A1, I1, A2, I2, RD, RE](
    e1: Codec[A1, I1, RD, RE], e2: Codec[A2, I2, RD, RE], /
) -> _Tuple[tuple[A1, A2], tuple[I1, I2], RD, RE]: ...
@overload
def Tuple[A1, I1, A2, I2, A3, I3, RD, RE](
    e1: Codec[A1, I1, RD, RE], e2: Codec[A2, I2, RD, RE], e3: Codec[A3, I3, RD, RE], /
) -> _Tuple[tuple[A1, A2, A3], tuple[I1, I2, I3], RD, RE]: ...
@overload
def Tuple[A1, I1, A2, I2, A3, I3, A4, I4, RD, RE](
    e1: Codec[A1, I1, RD, RE],
    e2: Codec[A2, I2, RD, RE],
    e3: Codec[A3, I3, RD, RE],
    e4: Codec[A4, I4, RD, RE],
    /,
) -> _Tuple[tuple[A1, A2, A3, A4], tuple[I1, I2, I3, I4], RD, RE]: ...
@overload
def Tuple[A1, I1, A2, I2, A3, I3, A4, I4, A5, I5, RD, RE](
    e1: Codec[A1, I1, RD, RE],
    e2: Codec[A2, I2, RD, RE],
    e3: Codec[A3, I3, RD, RE],
    e4: Codec[A4, I4, RD, RE],
    e5: Codec[A5, I5, RD, RE],
    /,
) -> _Tuple[tuple[A1, A2, A3, A4, A5], tuple[I1, I2, I3, I4, I5], RD, RE]: ...
@overload
def Tuple[A1, I1, A2, I2, A3, I3, A4, I4, A5, I5, A6, I6, RD, RE](
    e1: Codec[A1, I1, RD, RE],
    e2: Codec[A2, I2, RD, RE],
    e3: Codec[A3, I3, RD, RE],
    e4: Codec[A4, I4, RD, RE],
    e5: Codec[A5, I5, RD, RE],
    e6: Codec[A6, I6, RD, RE],
    /,
) -> _Tuple[tuple[A1, A2, A3, A4, A5, A6], tuple[I1, I2, I3, I4, I5, I6], RD, RE]: ...
@overload
def Tuple[A1, I1, A2, I2, A3, I3, A4, I4, A5, I5, A6, I6, A7, I7, RD, RE](
    e1: Codec[A1, I1, RD, RE],
    e2: Codec[A2, I2, RD, RE],
    e3: Codec[A3, I3, RD, RE],
    e4: Codec[A4, I4, RD, RE],
    e5: Codec[A5, I5, RD, RE],
    e6: Codec[A6, I6, RD, RE],
    e7: Codec[A7, I7, RD, RE],
    /,
) -> _Tuple[tuple[A1, A2, A3, A4, A5, A6, A7], tuple[I1, I2, I3, I4, I5, I6, I7], RD, RE]: ...
@overload
def Tuple[A1, I1, A2, I2, A3, I3, A4, I4, A5, I5, A6, I6, A7, I7, A8, I8, RD, RE](
    e1: Codec[A1, I1, RD, RE],
    e2: Codec[A2, I2, RD, RE],
    e3: Codec[A3, I3, RD, RE],
    e4: Codec[A4, I4, RD, RE],
    e5: Codec[A5, I5, RD, RE],
    e6: Codec[A6, I6, RD, RE],
    e7: Codec[A7, I7, RD, RE],
    e8: Codec[A8, I8, RD, RE],
    /,
) -> _Tuple[
    tuple[A1, A2, A3, A4, A5, A6, A7, A8], tuple[I1, I2, I3, I4, I5, I6, I7, I8], RD, RE
]: ...
@overload
def Tuple[A, I, RD, RE](
    *elements: Codec[A, I, RD, RE] | OptionalKey[A, I, RD, RE],
) -> _Tuple[tuple[A, ...], tuple[I, ...], RD, RE]: ...
def Tuple(*elements: TupleElement) -> TupleSchema[Any, Any, Any, Any]:
    """A tuple of one value per element (Effect's ``Tuple``): a missing
    element is a ``Missing key`` issue, an extra position ``Expected no
    excess property``."""
    return TupleSchema(ast.Arrays(tuple(map(_element, elements))), elements)

TupleWithRest

TupleWithRest[B, J, RD, RE](schema: TupleSchema[tuple[], tuple[], RD, RE], rest: Codec[B, J, RD, RE], /) -> _Rest[tuple[B, ...], tuple[J, ...], RD, RE]
TupleWithRest[A1, I1, B, J, RD, RE](schema: TupleSchema[tuple[A1], tuple[I1], RD, RE], rest: Codec[B, J, RD, RE], /) -> _Rest[tuple[A1, *(tuple[B, ...])], tuple[I1, *(tuple[J, ...])], RD, RE]
TupleWithRest[A1, I1, A2, I2, B, J, RD, RE](schema: TupleSchema[tuple[A1, A2], tuple[I1, I2], RD, RE], rest: Codec[B, J, RD, RE], /) -> _Rest[tuple[A1, A2, *(tuple[B, ...])], tuple[I1, I2, *(tuple[J, ...])], RD, RE]
TupleWithRest[A1, I1, A2, I2, A3, I3, B, J, RD, RE](schema: TupleSchema[tuple[A1, A2, A3], tuple[I1, I2, I3], RD, RE], rest: Codec[B, J, RD, RE], /) -> _Rest[tuple[A1, A2, A3, *(tuple[B, ...])], tuple[I1, I2, I3, *(tuple[J, ...])], RD, RE]
TupleWithRest[B, J, C, K, RD, RE](schema: TupleSchema[tuple[], tuple[], RD, RE], rest: Codec[B, J, RD, RE], last: Codec[C, K, RD, RE], /) -> _Rest[tuple[*(tuple[B, ...]), C], tuple[*(tuple[J, ...]), K], RD, RE]
TupleWithRest[A1, I1, B, J, C, K, RD, RE](schema: TupleSchema[tuple[A1], tuple[I1], RD, RE], rest: Codec[B, J, RD, RE], last: Codec[C, K, RD, RE], /) -> _Rest[tuple[A1, *(tuple[B, ...]), C], tuple[I1, *(tuple[J, ...]), K], RD, RE]
TupleWithRest[A1, I1, A2, I2, B, J, C, K, RD, RE](schema: TupleSchema[tuple[A1, A2], tuple[I1, I2], RD, RE], rest: Codec[B, J, RD, RE], last: Codec[C, K, RD, RE], /) -> _Rest[tuple[A1, A2, *(tuple[B, ...]), C], tuple[I1, I2, *(tuple[J, ...]), K], RD, RE]
TupleWithRest[A, I, RD, RE](schema: TupleSchema[tuple[A, ...], tuple[I, ...], RD, RE], rest: Codec[A, I, RD, RE], /, *post: Codec[A, I, RD, RE] = ()) -> _Rest[tuple[A, ...], tuple[I, ...], RD, RE]

schema's elements, then any number of rest values, then one value of each post schema (Effect's TupleWithRest(schema, [rest, ...post])). Its checks are kept. The rest schemas are never optional (their type is Codec), and after an optional element no post schema may follow (ValueError).

ParameterTypeDescription
schema
rest
post= ()
@overload
def TupleWithRest[B, J, RD, RE](
    schema: TupleSchema[tuple[()], tuple[()], RD, RE], rest: Codec[B, J, RD, RE], /
) -> _Rest[tuple[B, ...], tuple[J, ...], RD, RE]: ...
@overload
def TupleWithRest[A1, I1, B, J, RD, RE](
    schema: TupleSchema[tuple[A1], tuple[I1], RD, RE], rest: Codec[B, J, RD, RE], /
) -> _Rest[tuple[A1, *tuple[B, ...]], tuple[I1, *tuple[J, ...]], RD, RE]: ...
@overload
def TupleWithRest[A1, I1, A2, I2, B, J, RD, RE](
    schema: TupleSchema[tuple[A1, A2], tuple[I1, I2], RD, RE], rest: Codec[B, J, RD, RE], /
) -> _Rest[tuple[A1, A2, *tuple[B, ...]], tuple[I1, I2, *tuple[J, ...]], RD, RE]: ...
@overload
def TupleWithRest[A1, I1, A2, I2, A3, I3, B, J, RD, RE](
    schema: TupleSchema[tuple[A1, A2, A3], tuple[I1, I2, I3], RD, RE],
    rest: Codec[B, J, RD, RE],
    /,
) -> _Rest[tuple[A1, A2, A3, *tuple[B, ...]], tuple[I1, I2, I3, *tuple[J, ...]], RD, RE]: ...
@overload
def TupleWithRest[B, J, C, K, RD, RE](
    schema: TupleSchema[tuple[()], tuple[()], RD, RE],
    rest: Codec[B, J, RD, RE],
    last: Codec[C, K, RD, RE],
    /,
) -> _Rest[tuple[*tuple[B, ...], C], tuple[*tuple[J, ...], K], RD, RE]: ...
@overload
def TupleWithRest[A1, I1, B, J, C, K, RD, RE](
    schema: TupleSchema[tuple[A1], tuple[I1], RD, RE],
    rest: Codec[B, J, RD, RE],
    last: Codec[C, K, RD, RE],
    /,
) -> _Rest[tuple[A1, *tuple[B, ...], C], tuple[I1, *tuple[J, ...], K], RD, RE]: ...
@overload
def TupleWithRest[A1, I1, A2, I2, B, J, C, K, RD, RE](
    schema: TupleSchema[tuple[A1, A2], tuple[I1, I2], RD, RE],
    rest: Codec[B, J, RD, RE],
    last: Codec[C, K, RD, RE],
    /,
) -> _Rest[tuple[A1, A2, *tuple[B, ...], C], tuple[I1, I2, *tuple[J, ...], K], RD, RE]: ...
@overload
def TupleWithRest[A, I, RD, RE](
    schema: TupleSchema[tuple[A, ...], tuple[I, ...], RD, RE],
    rest: Codec[A, I, RD, RE],
    /,
    *post: Codec[A, I, RD, RE],
) -> _Rest[tuple[A, ...], tuple[I, ...], RD, RE]: ...
def TupleWithRest(
    schema: TupleSchema[Any, Any, Any, Any],
    rest: Codec[Any, Any, Any, Any],
    /,
    *post: Codec[Any, Any, Any, Any],
) -> TupleWithRestSchema[Any, Any, Any, Any]:
    """``schema``'s elements, then any number of ``rest`` values, then one
    value of each ``post`` schema (Effect's ``TupleWithRest(schema, [rest,
    ...post])``). Its checks are kept. The rest schemas are never optional
    (their type is ``Codec``), and after an optional element no ``post``
    schema may follow (``ValueError``)."""
    rests = (rest, *post)
    node = cast("ast.Arrays", schema.ast)
    arrays = ast.tuple_with_rest(node, [r.__codec__().ast for r in rests])
    return TupleWithRestSchema(arrays, schema, rests)

UniqueArray

UniqueArray[A, I, RD, RE](value) -> ArraySchema[tuple[A, ...], A, I, RD, RE]

Array(value) whose values are all different (is_unique).

ParameterTypeDescription
valueCodec[A, I, RD, RE]

Returns ArraySchema[tuple[A, ...], A, I, RD, RE]

def UniqueArray[A, I, RD, RE](
    value: Codec[A, I, RD, RE], /
) -> ArraySchema[tuple[A, ...], A, I, RD, RE]:
    """``Array(value)`` whose values are all different (``is_unique``)."""
    return Array(value).check(is_unique())

optional_key

optional_key[A, I, RD, RE](schema) -> OptionalKey[A, I, RD, RE]

schema as a tuple element that may be missing (an optional one stays as it is); it must come after every required element (else ValueError).

ParameterTypeDescription
schemaCodec[A, I, RD, RE] | OptionalKey[A, I, RD, RE]

Returns OptionalKey[A, I, RD, RE]

def optional_key[A, I, RD, RE](
    schema: Codec[A, I, RD, RE] | OptionalKey[A, I, RD, RE], /
) -> OptionalKey[A, I, RD, RE]:
    """``schema`` as a tuple element that may be missing (an optional one
    stays as it is); it must come after every required element (else
    ``ValueError``)."""
    return schema if isinstance(schema, OptionalKey) else OptionalKey(schema)

is_finite

is_finite(**annotations) -> Filter[float]

Not NaN nor an infinity.

ParameterTypeDescription
annotationsobject = {}

Returns Filter[float]

def is_finite(**annotations: object) -> Filter[float]:
    """Not ``NaN`` nor an infinity."""
    return filter_of(
        _is_finite_number,
        {"expected": "a finite number", **_representation("isFinite", None), **annotations},
    )

is_int

is_int(**annotations) -> Filter[float]

A safe integer, as an int or a float.

ParameterTypeDescription
annotationsobject = {}

Returns Filter[float]

def is_int(**annotations: object) -> Filter[float]:
    """A safe integer, as an ``int`` or a ``float``."""
    return filter_of(
        _is_safe_integer,
        {"expected": "an integer", **_representation("isInt", None), **annotations},
    )

is_int32

is_int32(**annotations) -> FilterGroup[float]

An integer from -2 ** 31 to 2 ** 31 - 1.

ParameterTypeDescription
annotationsobject = {}

Returns FilterGroup[float]

def is_int32(**annotations: object) -> FilterGroup[float]:
    """An integer from ``-2 ** 31`` to ``2 ** 31 - 1``."""
    return FilterGroup(
        (is_int(), is_between(minimum=-2147483648, maximum=2147483647)),
        {"expected": "a 32-bit integer", **annotations},
    )

is_multiple_of

is_multiple_of(divisor, **annotations) -> Filter[float]

A multiple of divisor (its sign ignored), decided on the numbers' shortest decimal spellings: 0.3 is a multiple of 0.1. A zero or non-finite divisor raises ValueError.

ParameterTypeDescription
divisorfloat
annotationsobject = {}

Returns Filter[float]

def is_multiple_of(divisor: float, /, **annotations: object) -> Filter[float]:
    """A multiple of ``divisor`` (its sign ignored), decided on the numbers'
    shortest decimal spellings: ``0.3`` is a multiple of ``0.1``. A zero or
    non-finite divisor raises ``ValueError``."""
    if not (isinstance(divisor, int) or math.isfinite(divisor)) or divisor == 0:
        raise ValueError(f"Expected a finite non-zero number, got {js_number(divisor)}")
    divisor = abs(divisor)
    return filter_of(
        lambda n: _is_multiple(n, divisor),
        {
            "expected": f"a value that is a multiple of {js_number(divisor)}",
            **_representation("isMultipleOf", {"divisor": divisor}),
            **annotations,
        },
    )

is_uint32

is_uint32(**annotations) -> FilterGroup[float]

An integer from 0 to 2 ** 32 - 1.

ParameterTypeDescription
annotationsobject = {}

Returns FilterGroup[float]

def is_uint32(**annotations: object) -> FilterGroup[float]:
    """An integer from ``0`` to ``2 ** 32 - 1``."""
    return FilterGroup(
        (is_int(), is_between(minimum=0, maximum=4294967295)),
        {"expected": "a 32-bit unsigned integer", **annotations},
    )

make_is_between

make_is_between[T: SupportsOrder](*, formatter=format_unknown, annotate=None) -> Between[T]

annotate(minimum, maximum, exclusive_minimum, exclusive_maximum).

ParameterTypeDescription
formatterCallable[[T], str] = format_unknown
annotateAnnotateBetween[T] | None = None

Returns Between[T]

def make_is_between[T: SupportsOrder](
    *, formatter: Callable[[T], str] = format_unknown, annotate: AnnotateBetween[T] | None = None
) -> Between[T]:
    """``annotate(minimum, maximum, exclusive_minimum, exclusive_maximum)``."""

    def make(
        *,
        minimum: T,
        maximum: T,
        exclusive_minimum: bool = False,
        exclusive_maximum: bool = False,
        **annotations: object,
    ) -> Filter[T]:
        def accepts(input: T) -> bool:
            above = input > minimum if exclusive_minimum else input >= minimum
            below = input < maximum if exclusive_maximum else input <= maximum
            return above and below

        low = formatter(minimum) + (" (excluded)" if exclusive_minimum else "")
        high = formatter(maximum) + (" (excluded)" if exclusive_maximum else "")
        extra: Mapping[str, object] = (
            annotate(minimum, maximum, exclusive_minimum, exclusive_maximum)
            if annotate is not None
            else {}
        )
        return filter_of(
            accepts, {"expected": f"a value between {low} and {high}", **extra, **annotations}
        )

    return make

make_is_greater_than

make_is_greater_than[T: SupportsOrder](*, formatter=format_unknown, annotate=None) -> Bound[T]
ParameterTypeDescription
formatterCallable[[T], str] = format_unknown
annotateAnnotate[T] | None = None

Returns Bound[T]

def make_is_greater_than[T: SupportsOrder](
    *, formatter: Callable[[T], str] = format_unknown, annotate: Annotate[T] | None = None
) -> Bound[T]:
    return _bound(lambda a, b: a > b, "greater than", formatter, annotate)

make_is_greater_than_or_equal_to

make_is_greater_than_or_equal_to[T: SupportsOrder](*, formatter=format_unknown, annotate=None) -> Bound[T]
ParameterTypeDescription
formatterCallable[[T], str] = format_unknown
annotateAnnotate[T] | None = None

Returns Bound[T]

def make_is_greater_than_or_equal_to[T: SupportsOrder](
    *, formatter: Callable[[T], str] = format_unknown, annotate: Annotate[T] | None = None
) -> Bound[T]:
    return _bound(lambda a, b: a >= b, "greater than or equal to", formatter, annotate)

make_is_less_than

make_is_less_than[T: SupportsOrder](*, formatter=format_unknown, annotate=None) -> Bound[T]
ParameterTypeDescription
formatterCallable[[T], str] = format_unknown
annotateAnnotate[T] | None = None

Returns Bound[T]

def make_is_less_than[T: SupportsOrder](
    *, formatter: Callable[[T], str] = format_unknown, annotate: Annotate[T] | None = None
) -> Bound[T]:
    return _bound(lambda a, b: a < b, "less than", formatter, annotate)

make_is_less_than_or_equal_to

make_is_less_than_or_equal_to[T: SupportsOrder](*, formatter=format_unknown, annotate=None) -> Bound[T]
ParameterTypeDescription
formatterCallable[[T], str] = format_unknown
annotateAnnotate[T] | None = None

Returns Bound[T]

def make_is_less_than_or_equal_to[T: SupportsOrder](
    *, formatter: Callable[[T], str] = format_unknown, annotate: Annotate[T] | None = None
) -> Bound[T]:
    return _bound(lambda a, b: a <= b, "less than or equal to", formatter, annotate)

make_is_multiple_of

make_is_multiple_of[T](*, is_multiple, formatter=format_unknown, annotate=None) -> Bound[T]

is_multiple(input, divisor) decides (Effect takes a remainder function and its zero).

ParameterTypeDescription
is_multipleCallable[[T, T], bool]
formatterCallable[[T], str] = format_unknown
annotateAnnotate[T] | None = None

Returns Bound[T]

def make_is_multiple_of[T](
    *,
    is_multiple: Callable[[T, T], bool],
    formatter: Callable[[T], str] = format_unknown,
    annotate: Annotate[T] | None = None,
) -> Bound[T]:
    """``is_multiple(input, divisor)`` decides (Effect takes a remainder
    function and its zero)."""

    def make(divisor: T, /, **annotations: object) -> Filter[T]:
        extra: Mapping[str, object] = annotate(divisor) if annotate is not None else {}
        return filter_of(
            lambda input: is_multiple(input, divisor),
            {
                "expected": f"a value that is a multiple of {formatter(divisor)}",
                **extra,
                **annotations,
            },
        )

    return make

is_between_code_points

is_between_code_points(minimum, maximum, **annotations) -> Filter[str]
ParameterTypeDescription
minimumfloat
maximumfloat
annotationsobject = {}

Returns Filter[str]

def is_between_code_points(minimum: float, maximum: float, /, **annotations: object) -> Filter[str]:
    low, high = _cardinality(minimum), _cardinality(maximum)
    return _sized(
        lambda count: low <= count <= high,
        _between(
            low,
            high,
            f"a string with {low} code points",
            f"a string with between {low} and {high} code points",
        ),
        "isBetweenCodePoints",
        {"minimum": low, "maximum": high},
        annotations,
        structural=False,
    )

is_between_length

is_between_length(minimum, maximum, **annotations) -> Filter[Sized]
ParameterTypeDescription
minimumfloat
maximumfloat
annotationsobject = {}

Returns Filter[Sized]

def is_between_length(minimum: float, maximum: float, /, **annotations: object) -> Filter[Sized]:
    low, high = _cardinality(minimum), _cardinality(maximum)
    return _sized(
        lambda length: low <= length <= high,
        _between(
            low,
            high,
            f"a value with a length of {low}",
            f"a value with a length between {low} and {high}",
        ),
        "isBetweenLength",
        {"minimum": low, "maximum": high},
        annotations,
    )

is_between_properties

is_between_properties(minimum, maximum, **annotations) -> Filter[Sized]
ParameterTypeDescription
minimumfloat
maximumfloat
annotationsobject = {}

Returns Filter[Sized]

def is_between_properties(
    minimum: float, maximum: float, /, **annotations: object
) -> Filter[Sized]:
    low, high = _cardinality(minimum), _cardinality(maximum)
    return _sized(
        lambda count: low <= count <= high,
        _between(
            low,
            high,
            f"a value with exactly {_entries(low)}",
            f"a value with between {low} and {high} entries",
        ),
        "isBetweenProperties",
        {"minimum": low, "maximum": high},
        annotations,
    )

is_between_size

is_between_size(minimum, maximum, **annotations) -> Filter[Sized]
ParameterTypeDescription
minimumfloat
maximumfloat
annotationsobject = {}

Returns Filter[Sized]

def is_between_size(minimum: float, maximum: float, /, **annotations: object) -> Filter[Sized]:
    low, high = _cardinality(minimum), _cardinality(maximum)
    return _sized(
        lambda size: low <= size <= high,
        _between(
            low,
            high,
            f"a value with a size of {low}",
            f"a value with a size between {low} and {high}",
        ),
        "isBetweenSize",
        {"minimum": low, "maximum": high},
        annotations,
    )

is_max_code_points

is_max_code_points(max_code_points, **annotations) -> Filter[str]
ParameterTypeDescription
max_code_pointsfloat
annotationsobject = {}

Returns Filter[str]

def is_max_code_points(max_code_points: float, /, **annotations: object) -> Filter[str]:
    n = _cardinality(max_code_points)
    return _sized(
        lambda count: count <= n,
        f"a string with at most {n} code points",
        "isMaxCodePoints",
        {"maxCodePoints": n},
        annotations,
        structural=False,
    )

is_max_length

is_max_length(max_length, **annotations) -> Filter[Sized]
ParameterTypeDescription
max_lengthfloat
annotationsobject = {}

Returns Filter[Sized]

def is_max_length(max_length: float, /, **annotations: object) -> Filter[Sized]:
    n = _cardinality(max_length)
    return _sized(
        lambda length: length <= n,
        f"a value with a length of at most {n}",
        "isMaxLength",
        {"maxLength": n},
        annotations,
    )

is_max_properties

is_max_properties(max_properties, **annotations) -> Filter[Sized]
ParameterTypeDescription
max_propertiesfloat
annotationsobject = {}

Returns Filter[Sized]

def is_max_properties(max_properties: float, /, **annotations: object) -> Filter[Sized]:
    n = _cardinality(max_properties)
    return _sized(
        lambda count: count <= n,
        f"a value with at most {_entries(n)}",
        "isMaxProperties",
        {"maxProperties": n},
        annotations,
    )

is_max_size

is_max_size(max_size, **annotations) -> Filter[Sized]
ParameterTypeDescription
max_sizefloat
annotationsobject = {}

Returns Filter[Sized]

def is_max_size(max_size: float, /, **annotations: object) -> Filter[Sized]:
    n = _cardinality(max_size)
    return _sized(
        lambda size: size <= n,
        f"a value with a size of at most {n}",
        "isMaxSize",
        {"maxSize": n},
        annotations,
    )

is_min_code_points

is_min_code_points(min_code_points, **annotations) -> Filter[str]
ParameterTypeDescription
min_code_pointsfloat
annotationsobject = {}

Returns Filter[str]

def is_min_code_points(min_code_points: float, /, **annotations: object) -> Filter[str]:
    n = _cardinality(min_code_points)
    return _sized(
        lambda count: count >= n,
        f"a string with at least {n} code points",
        "isMinCodePoints",
        {"minCodePoints": n},
        annotations,
        structural=False,
    )

is_min_length

is_min_length(min_length, **annotations) -> Filter[Sized]
ParameterTypeDescription
min_lengthfloat
annotationsobject = {}

Returns Filter[Sized]

def is_min_length(min_length: float, /, **annotations: object) -> Filter[Sized]:
    n = _cardinality(min_length)
    return _sized(
        lambda length: length >= n,
        f"a value with a length of at least {n}",
        "isMinLength",
        {"minLength": n},
        annotations,
    )

is_min_properties

is_min_properties(min_properties, **annotations) -> Filter[Sized]
ParameterTypeDescription
min_propertiesfloat
annotationsobject = {}

Returns Filter[Sized]

def is_min_properties(min_properties: float, /, **annotations: object) -> Filter[Sized]:
    n = _cardinality(min_properties)
    return _sized(
        lambda count: count >= n,
        f"a value with at least {_entries(n)}",
        "isMinProperties",
        {"minProperties": n},
        annotations,
    )

is_min_size

is_min_size(min_size, **annotations) -> Filter[Sized]
ParameterTypeDescription
min_sizefloat
annotationsobject = {}

Returns Filter[Sized]

def is_min_size(min_size: float, /, **annotations: object) -> Filter[Sized]:
    n = _cardinality(min_size)
    return _sized(
        lambda size: size >= n,
        f"a value with a size of at least {n}",
        "isMinSize",
        {"minSize": n},
        annotations,
    )

is_non_empty

is_non_empty(**annotations) -> Filter[Sized]

is_min_length(1).

ParameterTypeDescription
annotationsobject = {}

Returns Filter[Sized]

def is_non_empty(**annotations: object) -> Filter[Sized]:
    """``is_min_length(1)``."""
    return is_min_length(1, **annotations)

is_property_names

is_property_names(key_schema, **annotations) -> Filter[Mapping[Any, object]]

A mapping whose every key is a value of key_schema's encoded side; each bad key's issue is reported at that key.

ParameterTypeDescription
key_schemaTop
annotationsobject = {}

Returns Filter[Mapping[Any, object]]

def is_property_names(key_schema: Top, /, **annotations: object) -> Filter[Mapping[Any, object]]:
    """A mapping whose every key is a value of ``key_schema``'s encoded
    side; each bad key's issue is reported at that key."""
    keys = key_schema.__codec__().ast.flip().to_type()

    def run(input: Mapping[Any, object], ast: AST, options: ParseOptions) -> Issue | None:
        issues: list[Issue] = []
        for key in input:
            match run_now(keys.parse(key, options)):
                case Success():
                    pass
                case failure:
                    issue = issue_of(failure)
                    if issue is None:
                        raise failure.cause.raisable()
                    issues.append(Pointer((key,), issue))
                    if options.get("errors") == "first":
                        break
        if not issues:
            return None
        return Composite(ast, (issues[0], *issues[1:]), reported(input, options))

    return Filter(
        run,
        {
            "expected": "an object with property names matching the schema",
            STRUCTURAL: True,
            "representation": {
                "id": "effect/schema/isPropertyNames",
                "payload": None,
                "schemas": (key_schema.__codec__().ast,),
            },
            **annotations,
        },
    )

is_unique

is_unique(**annotations) -> Filter[Sequence[object]]

A sequence with no two items Equal.equals calls equal (True is not 1, NaN is NaN).

ParameterTypeDescription
annotationsobject = {}

Returns Filter[Sequence[object]]

def is_unique(**annotations: object) -> Filter[Sequence[object]]:
    """A sequence with no two items ``Equal.equals`` calls equal (``True``
    is not ``1``, NaN is NaN)."""
    return filter_of(
        _all_unique,
        {
            "expected": "an array with unique items",
            "representation": {"id": "effect/schema/isUnique", "payload": None},
            **annotations,
        },
    )

is_unique_key

is_unique_key(**annotations) -> Filter[Sequence[tuple[object, object]]]

A sequence of pairs with no two equal keys.

ParameterTypeDescription
annotationsobject = {}

Returns Filter[Sequence[tuple[object, object]]]

def is_unique_key(**annotations: object) -> Filter[Sequence[tuple[object, object]]]:
    """A sequence of pairs with no two equal keys."""
    return filter_of(
        lambda pairs: _all_unique([key for key, _ in pairs]),
        {
            "expected": "an array with unique keys",
            "representation": {"id": "effect/schema/isUniqueKey", "payload": None},
            **annotations,
        },
    )

is_ascii

is_ascii(**annotations) -> Filter[str]

Only ASCII characters (U+0000 to U+007F), the empty string included.

ParameterTypeDescription
annotationsobject = {}

Returns Filter[str]

def is_ascii(**annotations: object) -> Filter[str]:
    """Only ASCII characters (``U+0000`` to ``U+007F``), the empty string included."""
    return string_filter(
        lambda s: _ASCII.fullmatch(s) is not None, "an ASCII string", "isAscii", None, annotations
    )

is_base64

is_base64(**annotations) -> Filter[str]
ParameterTypeDescription
annotationsobject = {}

Returns Filter[str]

def is_base64(**annotations: object) -> Filter[str]:
    return string_filter(
        lambda s: len(s) % 4 == 0 and _BASE64.fullmatch(s) is not None,
        "a base64 encoded string",
        "isBase64",
        None,
        annotations,
    )

is_base64_url

is_base64_url(**annotations) -> Filter[str]
ParameterTypeDescription
annotationsobject = {}

Returns Filter[str]

def is_base64_url(**annotations: object) -> Filter[str]:
    return string_filter(
        lambda s: (
            _BASE64_URL.fullmatch(s) is not None
            and (len(s) % 4 == 0 if s.endswith("=") else len(s) % 4 != 1)
        ),
        "a base64url encoded string",
        "isBase64Url",
        None,
        annotations,
    )

is_capitalized

is_capitalized(**annotations) -> Filter[str]

A string whose first character (if any) is uppercase.

ParameterTypeDescription
annotationsobject = {}

Returns Filter[str]

def is_capitalized(**annotations: object) -> Filter[str]:
    """A string whose first character (if any) is uppercase."""
    return string_filter(
        lambda s: s[:1].upper() == s[:1],
        "a string with the first character in uppercase",
        "isCapitalized",
        None,
        annotations,
    )

is_ending_with

is_ending_with(suffix, **annotations) -> Filter[str]
ParameterTypeDescription
suffixstr
annotationsobject = {}

Returns Filter[str]

def is_ending_with(suffix: str, /, **annotations: object) -> Filter[str]:
    return string_filter(
        lambda s: s.endswith(suffix),
        f"a string ending with {json_quote(suffix)}",
        "isEndingWith",
        {"endsWith": suffix},
        annotations,
    )

is_guid

is_guid(**annotations) -> Filter[str]
ParameterTypeDescription
annotationsobject = {}

Returns Filter[str]

def is_guid(**annotations: object) -> Filter[str]:
    return string_filter(_search(js_regex(_GUID)), "a GUID", "isGUID", None, annotations)

is_including

is_including(part, **annotations) -> Filter[str]
ParameterTypeDescription
partstr
annotationsobject = {}

Returns Filter[str]

def is_including(part: str, /, **annotations: object) -> Filter[str]:
    return string_filter(
        lambda s: part in s,
        f"a string including {json_quote(part)}",
        "isIncluding",
        {"includes": part},
        annotations,
    )

is_lowercased

is_lowercased(**annotations) -> Filter[str]
ParameterTypeDescription
annotationsobject = {}

Returns Filter[str]

def is_lowercased(**annotations: object) -> Filter[str]:
    return string_filter(
        lambda s: s.lower() == s,
        "a string with all characters in lowercase",
        "isLowercased",
        None,
        annotations,
    )

is_pattern

is_pattern(pattern, **annotations) -> Filter[str]

A string pattern finds a match in (re.search).

ParameterTypeDescription
patternre.Pattern[str] | str
annotationsobject = {}

Returns Filter[str]

def is_pattern(pattern: re.Pattern[str] | str, /, **annotations: object) -> Filter[str]:
    """A string ``pattern`` finds a match in (``re.search``)."""
    regex = re.compile(pattern) if isinstance(pattern, str) else pattern
    return _pattern(regex, regex.pattern, annotations)

is_starting_with

is_starting_with(prefix, **annotations) -> Filter[str]
ParameterTypeDescription
prefixstr
annotationsobject = {}

Returns Filter[str]

def is_starting_with(prefix: str, /, **annotations: object) -> Filter[str]:
    return string_filter(
        lambda s: s.startswith(prefix),
        f"a string starting with {json_quote(prefix)}",
        "isStartingWith",
        {"startsWith": prefix},
        annotations,
    )

is_string_big_int

is_string_big_int(**annotations) -> Filter[str]

A string spelling an integer ("-12"; no +).

ParameterTypeDescription
annotationsobject = {}

Returns Filter[str]

def is_string_big_int(**annotations: object) -> Filter[str]:
    """A string spelling an integer (``"-12"``; no ``+``)."""
    return string_filter(
        _search(_BIGINT),
        "a string representing a bigint",
        "isStringBigInt",
        None,
        annotations,
    )

is_string_finite

is_string_finite(**annotations) -> Filter[str]

A string spelling a finite number ("1", "-.5E+5").

ParameterTypeDescription
annotationsobject = {}

Returns Filter[str]

def is_string_finite(**annotations: object) -> Filter[str]:
    """A string spelling a finite number (``"1"``, ``"-.5E+5"``)."""
    return string_filter(
        _search(_FINITE),
        "a string representing a finite number",
        "isStringFinite",
        None,
        annotations,
    )

is_trimmed

is_trimmed(**annotations) -> Filter[str]

A string with no leading or trailing whitespace (JavaScript's).

ParameterTypeDescription
annotationsobject = {}

Returns Filter[str]

def is_trimmed(**annotations: object) -> Filter[str]:
    """A string with no leading or trailing whitespace (JavaScript's)."""
    return string_filter(
        lambda s: trim(s) == s,
        "a string with no leading or trailing whitespace",
        "isTrimmed",
        None,
        annotations,
    )

is_ulid

is_ulid(**annotations) -> Filter[str]

A ULID; it fails with the pattern's text, as in Effect.

ParameterTypeDescription
annotationsobject = {}

Returns Filter[str]

def is_ulid(**annotations: object) -> Filter[str]:
    """A ULID; it fails with the pattern's text, as in Effect."""
    return string_filter(
        _search(js_regex(_ULID)),
        f"a string matching the RegExp {_ULID}",
        "isULID",
        None,
        annotations,
    )

is_uncapitalized

is_uncapitalized(**annotations) -> Filter[str]

A string whose first character (if any) is lowercase.

ParameterTypeDescription
annotationsobject = {}

Returns Filter[str]

def is_uncapitalized(**annotations: object) -> Filter[str]:
    """A string whose first character (if any) is lowercase."""
    return string_filter(
        lambda s: s[:1].lower() == s[:1],
        "a string with the first character in lowercase",
        "isUncapitalized",
        None,
        annotations,
    )

is_uppercased

is_uppercased(**annotations) -> Filter[str]
ParameterTypeDescription
annotationsobject = {}

Returns Filter[str]

def is_uppercased(**annotations: object) -> Filter[str]:
    return string_filter(
        lambda s: s.upper() == s,
        "a string with all characters in uppercase",
        "isUppercased",
        None,
        annotations,
    )

is_uuid

is_uuid(version=None, **annotations) -> Filter[str]

A UUID (any version, or the nil and max UUIDs), or one of version.

ParameterTypeDescription
versionUUIDVersion | None = None
annotationsobject = {}

Returns Filter[str]

def is_uuid(version: UUIDVersion | None = None, /, **annotations: object) -> Filter[str]:
    """A UUID (any version, or the nil and max UUIDs), or one of ``version``."""
    source = (
        _ANY_UUID
        if version is None
        else f"^([0-9a-fA-F]{{8}}-[0-9a-fA-F]{{4}}-{version}[0-9a-fA-F]{{3}}"
        "-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$"
    )
    return string_filter(
        _search(js_regex(source)),
        "a UUID" if version is None else f"a UUID v{version}",
        "isUUID",
        {"version": version},
        annotations,
    )

class_check

class_check[F: Callable[[Any], FilterOutput]](*, abort=False, **annotations) -> Callable[[F], F]

Mark a method of a schema class as a check of its instances (Effect's checks on a class's struct): it returns a FilterOutput (True / None to accept, False, a message, an issue, ...) and runs after the fields are valid, when constructing and when decoding. expected= / message= annotate the failure; abort=True stops the checks after it when it fails. Subclasses inherit the checks.

ParameterTypeDescription
abortbool = False
annotationsobject = {}

Returns Callable[[F], F]

def class_check[F: Callable[[Any], FilterOutput]](
    *, abort: bool = False, **annotations: object
) -> Callable[[F], F]:
    """Mark a method of a schema class as a check of its instances (Effect's
    checks on a class's struct): it returns a ``FilterOutput`` (``True`` /
    ``None`` to accept, ``False``, a message, an issue, ...) and runs after
    the fields are valid, when constructing and when decoding.
    ``expected=`` / ``message=`` annotate the failure; ``abort=True`` stops
    the checks after it when it fails. Subclasses inherit the checks."""

    def mark(method: F) -> F:
        setattr(method, _CHECK, filter_of(method, annotations or None, abort))
        return method

    return mark

field

field[A](schema: Codec[A, object, Never, Never], /, *, key: str | None = None) -> A
field[A](schema: Codec[A, object, Never, Never], /, *, default: A, key: str | None = None) -> A
field[A](schema: Codec[A, object, Never, Never], /, *, default_factory: Callable[[], A], key: str | None = None) -> A
field[A](*, default_factory: Callable[[], A], key: str | None = None) -> A
field[A](*, default: A, key: str) -> A
field(*, key: str) -> Any

A schema class field: schema instead of the annotation's (its Type must fit the annotation), a default or a default factory, and key, its name in the class's schema where that is not the attribute's: what it encodes to, decodes from and is called in decode issues, and what a mapping given to make holds it under. The constructor keeps the attribute's name.

ParameterTypeDescription
schema= None
default= MISSING
default_factory= None
key= None
@overload
def field[A](schema: Codec[A, object, Never, Never], /, *, key: str | None = None) -> A: ...
@overload
def field[A](
    schema: Codec[A, object, Never, Never], /, *, default: A, key: str | None = None
) -> A: ...
@overload
def field[A](
    schema: Codec[A, object, Never, Never],
    /,
    *,
    default_factory: Callable[[], A],
    key: str | None = None,
) -> A: ...
@overload
def field[A](*, default_factory: Callable[[], A], key: str | None = None) -> A: ...
@overload
def field[A](*, default: A, key: str) -> A: ...
@overload
def field(*, key: str) -> Any: ...
def field(
    schema: Codec[object, object, Never, Never] | None = None,
    /,
    *,
    default: object = MISSING,
    default_factory: Callable[[], object] | None = None,
    key: str | None = None,
) -> Any:
    """A schema class field: ``schema`` instead of the annotation's (its
    Type must fit the annotation), a default or a default factory, and
    ``key``, its name in the class's schema where that is not the attribute's:
    what it encodes to, decodes from and is called in decode issues, and what a
    mapping given to ``make`` holds it under. The constructor keeps the
    attribute's name."""
    metadata: dict[str, object] = {}
    if schema is not None:
        metadata[_SCHEMA] = schema
    if key is not None:
        metadata[_KEY] = key
    if default_factory is not None:
        return dataclasses.field(default_factory=default_factory, metadata=metadata)
    return dataclasses.field(default=default, metadata=metadata)

new

new[**P, T: _SchemaClass](cls, **options) -> Callable[P, T]

cls's constructor with options (Effect's new A(props, options)): S.new(A, disable_checks=True)(x=1) skips the fields' and the class's checks, still checking the fields' types and applying their defaults.

ParameterTypeDescription
clsCallable[P, T]
optionsUnpack[ParseOptions] = {}

Returns Callable[P, T]

def new[**P, T: _SchemaClass](
    cls: Callable[P, T], /, **options: Unpack[ParseOptions]
) -> Callable[P, T]:
    """``cls``'s constructor with options (Effect's ``new A(props, options)``):
    ``S.new(A, disable_checks=True)(x=1)`` skips the fields' and the class's
    checks, still checking the fields' types and applying their defaults."""
    klass = cast("type[_SchemaClass]", cls)
    shape = _shape_of(klass)

    def construct(*args: P.args, **kwargs: P.kwargs) -> T:
        instance = klass.__new__(klass)
        shape.init(instance, *args, **kwargs)
        shape.validate(instance, options)
        return cast("T", instance)

    return construct

ArrayEnsure

ArrayEnsure[A, I, RD, RE](schema) -> DecodeToSchema[tuple[A, ...], I | tuple[I, ...], RD, RE]

One value of schema or a sequence of them, decoded as a tuple; a one-element tuple encodes as its element (Effect's ArrayEnsure). The single value is tried first, so a schema that takes sequences decodes one as a single value.

ParameterTypeDescription
schemaCodec[A, I, RD, RE]

Returns DecodeToSchema[tuple[A, ...], I | tuple[I, ...], RD, RE]

def ArrayEnsure[A, I, RD, RE](
    schema: Codec[A, I, RD, RE], /
) -> DecodeToSchema[tuple[A, ...], I | tuple[I, ...], RD, RE]:
    """One value of ``schema`` or a sequence of them, decoded as a tuple; a
    one-element tuple encodes as its element (Effect's ``ArrayEnsure``). The
    single value is tried first, so a ``schema`` that takes sequences
    decodes one as a single value."""
    one_or_many: T.Transformation[tuple[object], object] = T.transform(decode=_one, encode=_only)
    one = schema.__codec__().pipe(decode_to(Tuple(Unknown), one_or_many))
    many = Array(schema)
    # ``one`` decodes to a one-element tuple of ``A`` (typed ``object`` by
    # its ``Tuple(Unknown)`` target), so the union's Type is a sequence of ``A``.
    source = cast("Bottom[Sequence[A], I | tuple[I, ...], RD, RE]", Union(one, many))
    return source.pipe(decode_to(Array(to_type(schema))))

NullOr

NullOr[A, I, RD, RE](schema) -> Bottom[A | None, I | None, RD, RE]

schema's values or None (Effect's NullOr).

ParameterTypeDescription
schemaCodec[A, I, RD, RE]

Returns Bottom[A | None, I | None, RD, RE]

def NullOr[A, I, RD, RE](schema: Codec[A, I, RD, RE], /) -> Bottom[A | None, I | None, RD, RE]:
    """``schema``'s values or ``None`` (Effect's ``NullOr``)."""
    return Union(schema, Null)

OptionFromNullOr

OptionFromNullOr[A, I, RD, RE](schema) -> DecodeToSchema[_Option[A], I | None, RD, RE]

None decoded as an empty Option, a value as Some(value) (Effect's OptionFromNullOr).

ParameterTypeDescription
schemaCodec[A, I, RD, RE]

Returns DecodeToSchema[_Option[A], I | None, RD, RE]

def OptionFromNullOr[A, I, RD, RE](
    schema: Codec[A, I, RD, RE], /
) -> DecodeToSchema[_Option[A], I | None, RD, RE]:
    """``None`` decoded as an empty ``Option``, a value as ``Some(value)``
    (Effect's ``OptionFromNullOr``)."""
    return NullOr(schema).pipe(decode_to(Option(to_type(schema)), T.option_from_null_or()))

OptionFromOptionalKey

OptionFromOptionalKey[A, I, RD, RE](schema) -> DecodeToSchema[_Option[A], I, RD, RE]

A missing struct key decoded as None, a present one as Some(value); None encodes to a missing key (Effect's OptionFromOptionalKey).

ParameterTypeDescription
schemaCodec[A, I, RD, RE]

Returns DecodeToSchema[_Option[A], I, RD, RE]

def OptionFromOptionalKey[A, I, RD, RE](
    schema: Codec[A, I, RD, RE], /
) -> DecodeToSchema[_Option[A], I, RD, RE]:
    """A missing struct key decoded as ``None``, a present one as
    ``Some(value)``; ``None`` encodes to a missing key (Effect's
    ``OptionFromOptionalKey``)."""
    return optional_key(schema).pipe(
        decode_to(Option(to_type(schema)), T.option_from_optional_key())
    )

OptionFromOptionalNullOr

OptionFromOptionalNullOr[A, I, RD, RE](schema, /, *, on_none_encoding='omit') -> DecodeToSchema[_Option[A], I | None, RD, RE]

A missing struct key or None decoded as an empty Option, a value as Some(value); an empty Option encodes to a missing key, or to None with on_none_encoding=None (Effect's OptionFromOptionalNullOr).

ParameterTypeDescription
schemaCodec[A, I, RD, RE]
on_none_encodingLiteral['omit'] | None = 'omit'

Returns DecodeToSchema[_Option[A], I | None, RD, RE]

def OptionFromOptionalNullOr[A, I, RD, RE](
    schema: Codec[A, I, RD, RE], /, *, on_none_encoding: Literal["omit"] | None = "omit"
) -> DecodeToSchema[_Option[A], I | None, RD, RE]:
    """A missing struct key or ``None`` decoded as an empty ``Option``, a
    value as ``Some(value)``; an empty ``Option`` encodes to a missing key,
    or to ``None`` with ``on_none_encoding=None`` (Effect's
    ``OptionFromOptionalNullOr``)."""
    encode = _flatten if on_none_encoding == "omit" else _null_unless_some
    transformation: T.Transformation[Any, Any] = T.Transformation(
        transform_optional(_some_unless_null), transform_optional(encode)
    )
    return optional_key(NullOr(schema)).pipe(decode_to(Option(to_type(schema)), transformation))

RedactedFromValue

RedactedFromValue[A, I, RD, RE](value, /, *, label=None, disallow_encode=False) -> DecodeToSchema[_Redacted[A], I, RD, RE]

A value decoded as a Redacted of it (with label); encoding reveals it unless disallow_encode (Effect's RedactedFromValue).

ParameterTypeDescription
valueCodec[A, I, RD, RE]
labelstr | None = None
disallow_encodebool = False

Returns DecodeToSchema[_Redacted[A], I, RD, RE]

def RedactedFromValue[A, I, RD, RE](
    value: Codec[A, I, RD, RE], /, *, label: str | None = None, disallow_encode: bool = False
) -> DecodeToSchema[_Redacted[A], I, RD, RE]:
    """A value decoded as a ``Redacted`` of it (with ``label``); encoding
    reveals it unless ``disallow_encode`` (Effect's ``RedactedFromValue``)."""
    encode: Any = forbidden(_cannot_encode) if disallow_encode else transform(_redacted.value)

    def wrap(secret: A) -> _Redacted[A]:
        return _redacted.make(secret, label=label)

    target = Redacted(to_type(value), label=label)
    return value.__codec__().pipe(decode_to(target, T.Transformation(transform(wrap), encode)))

from_json_string

from_json_string[A, I, RD, RE](schema, /, *, reviver=None, replacer=None, space=None) -> DecodeToSchema[A, str, RD, RE]

JSON text, parsed (with reviver) then decoded by schema (Effect's fromJsonString); encoding writes through replacer, indented by space.

ParameterTypeDescription
schemaCodec[A, I, RD, RE]
reviverG.JsonReviver | None = None
replacerG.JsonReplacer | None = None
spaceint | str | None = None

Returns DecodeToSchema[A, str, RD, RE]

def from_json_string[A, I, RD, RE](
    schema: Codec[A, I, RD, RE],
    /,
    *,
    reviver: G.JsonReviver | None = None,
    replacer: G.JsonReplacer | None = None,
    space: int | str | None = None,
) -> DecodeToSchema[A, str, RD, RE]:
    """JSON text, parsed (with ``reviver``) then decoded by ``schema``
    (Effect's ``fromJsonString``); encoding writes through ``replacer``,
    indented by ``space``."""
    transformation: T.Transformation[Any, str] = T.from_json_string(
        reviver=reviver, replacer=replacer, space=space
    )
    return _JSON_STRING.pipe(decode_to(schema, transformation))

FrozenSet

FrozenSet[A, I, RD, RE](value) -> FrozenSetSchema[A, I, RD, RE]

A set or frozenset of value's values, decoded to a frozenset (Effect's ReadonlySet). Anything else is Expected frozenset.

ParameterTypeDescription
valueCodec[A, I, RD, RE]

Returns FrozenSetSchema[A, I, RD, RE]

def FrozenSet[A, I, RD, RE](value: Codec[A, I, RD, RE], /) -> FrozenSetSchema[A, I, RD, RE]:
    """A ``set`` or ``frozenset`` of ``value``'s values, decoded to a
    ``frozenset`` (Effect's ``ReadonlySet``). Anything else is ``Expected
    frozenset``."""
    node = ast.Declaration(
        (value.__codec__().ast,),
        _set_run,
        annotations={
            "representation": {"id": "effect/schema/ReadonlySet", "payload": None},
            "expected": "frozenset",
            "to_codec": _set_codec,
            "to_codec_arbitrary": _arb.frozen_set,
            "to_equivalence": _inst.set_equivalence,
            "to_formatter": _inst.set_formatter,
        },
    )
    return FrozenSetSchema(node, value)

Map

Map[K, V, KI, VI, RD, RE](key, value) -> MapSchema[K, V, KI, VI, RD, RE]

A Mapping of key values to value values, decoded to a dict (Effect's ReadonlyMap). Anything else is Expected Mapping.

ParameterTypeDescription
keyCodec[K, KI, RD, RE]
valueCodec[V, VI, RD, RE]

Returns MapSchema[K, V, KI, VI, RD, RE]

def Map[K, V, KI, VI, RD, RE](
    key: Codec[K, KI, RD, RE], value: Codec[V, VI, RD, RE], /
) -> MapSchema[K, V, KI, VI, RD, RE]:
    """A ``Mapping`` of ``key`` values to ``value`` values, decoded to a
    ``dict`` (Effect's ``ReadonlyMap``). Anything else is ``Expected
    Mapping``."""
    nodes = (key.__codec__().ast, value.__codec__().ast)
    annotations = {
        "representation": {"id": "effect/schema/ReadonlyMap", "payload": None},
        "expected": "Mapping",
        "to_codec": _map_codec,
        "to_codec_arbitrary": _arb.map_,
        "to_equivalence": _inst.map_equivalence,
        "to_formatter": _inst.map_formatter,
    }
    node = ast.Declaration(nodes, _map_run, annotations=annotations)
    return MapSchema(node, key, value)

tag

tag[L: LiteralInput](literal) -> WithConstructorDefault[L, L, Never, Never]

Literal(literal) filled in by make (Effect's tag): a tagged struct's "_tag" field, S.Struct(A, _tag=S.tag("A")).

ParameterTypeDescription
literalL

Returns WithConstructorDefault[L, L, Never, Never]

def tag[L: LiteralInput](literal: L, /) -> WithConstructorDefault[L, L, Never, Never]:
    """``Literal(literal)`` filled in by ``make`` (Effect's ``tag``): a
    tagged struct's ``"_tag"`` field, ``S.Struct(A, _tag=S.tag("A"))``."""
    return with_constructor_default(succeed(literal))(Literal(literal))

with_constructor_default

with_constructor_default[T](default) -> ConstructorDefault[T]

The schema, its missing struct key or tuple element filled by default's value in make / make_option / make_effect (Effect's withConstructorDefault): S.String.pipe(S.with_constructor_default(fx.succeed("a"))). default may be asynchronous (then use make_effect) and may fail with an Issue.

ParameterTypeDescription
defaultEffect[T, Issue]

Returns ConstructorDefault[T]

def with_constructor_default[T](default: Effect[T, Issue], /) -> ConstructorDefault[T]:
    """The schema, its missing struct key or tuple element filled by
    ``default``'s value in ``make`` / ``make_option`` / ``make_effect``
    (Effect's ``withConstructorDefault``):
    ``S.String.pipe(S.with_constructor_default(fx.succeed("a")))``.
    ``default`` may be asynchronous (then use ``make_effect``) and may fail
    with an ``Issue``."""
    require_effect(default, "default")
    return ConstructorDefault(default)

Cause

Cause[E, EI, RD, RE](error, defect) -> CauseSchema[E, EI, RD, RE]

A Cause (Effect's Cause): each reason is parsed by CauseReason(error, defect), issues at ["reasons"][i]. Anything else is Expected Cause.

ParameterTypeDescription
errorCodec[E, EI, RD, RE]
defectDefectCodec[RD, RE]

Returns CauseSchema[E, EI, RD, RE]

def Cause[E, EI, RD, RE](
    error: Codec[E, EI, RD, RE], defect: DefectCodec[RD, RE], /
) -> CauseSchema[E, EI, RD, RE]:
    """A ``Cause`` (Effect's ``Cause``): each reason is parsed by
    ``CauseReason(error, defect)``, issues at ``["reasons"][i]``. Anything
    else is ``Expected Cause``."""
    return CauseSchema(
        _node(
            (error, defect),
            _cause_run,
            "Cause",
            _cause_codec,
            to_equivalence=_inst.cause_equivalence,
            to_formatter=_inst.cause_formatter,
        ),
        error,
        defect,
    )

CauseReason

CauseReason[E, EI, RD, RE](error, defect) -> CauseReasonSchema[E, EI, RD, RE]

A reason of a Cause (Effect's CauseReason): a Fail whose error error takes, a Die whose defect defect takes, or an Interrupt (kept as it is). The parsed reason has no annotations, as in Effect. Anything else is Expected Cause.Failure.

ParameterTypeDescription
errorCodec[E, EI, RD, RE]
defectDefectCodec[RD, RE]

Returns CauseReasonSchema[E, EI, RD, RE]

def CauseReason[E, EI, RD, RE](
    error: Codec[E, EI, RD, RE], defect: DefectCodec[RD, RE], /
) -> CauseReasonSchema[E, EI, RD, RE]:
    """A reason of a ``Cause`` (Effect's ``CauseReason``): a ``Fail`` whose
    error ``error`` takes, a ``Die`` whose defect ``defect`` takes, or an
    ``Interrupt`` (kept as it is). The parsed reason has no annotations, as
    in Effect. Anything else is ``Expected Cause.Failure``."""
    node = _node(
        (error, defect),
        _reason_run,
        "Cause.Failure",
        _reason_codec,
        representation_id="CauseReason",
        to_equivalence=_inst.reason_equivalence,
        to_formatter=_inst.reason_formatter,
    )
    return CauseReasonSchema(node, error, defect)

Exit

Exit[A, E, AI, EI, RD, RE](value, error, defect) -> ExitSchema[A, E, AI, EI, RD, RE]

An Exit (Effect's Exit): a Success of a value value (issues at ["value"]), or a Failure whose cause Cause(error, defect) takes (at ["cause"]).

ParameterTypeDescription
valueCodec[A, AI, RD, RE]
errorCodec[E, EI, RD, RE]
defectDefectCodec[RD, RE]

Returns ExitSchema[A, E, AI, EI, RD, RE]

def Exit[A, E, AI, EI, RD, RE](
    value: Codec[A, AI, RD, RE], error: Codec[E, EI, RD, RE], defect: DefectCodec[RD, RE], /
) -> ExitSchema[A, E, AI, EI, RD, RE]:
    """An ``Exit`` (Effect's ``Exit``): a ``Success`` of a ``value`` value
    (issues at ``["value"]``), or a ``Failure`` whose cause
    ``Cause(error, defect)`` takes (at ``["cause"]``)."""
    node = _node(
        (value, error, defect),
        _exit_run,
        "Exit",
        _exit_codec,
        to_equivalence=_inst.exit_equivalence,
        to_formatter=_inst.exit_formatter,
    )
    return ExitSchema(node, value, error, defect)

Option

Option[A, I, RD, RE](value) -> OptionSchema[A, I, RD, RE]

An Option: None, or Some of a value of value (Effect's Option). Anything else is Expected Option.

ParameterTypeDescription
valueCodec[A, I, RD, RE]

Returns OptionSchema[A, I, RD, RE]

def Option[A, I, RD, RE](value: Codec[A, I, RD, RE], /) -> OptionSchema[A, I, RD, RE]:
    """An ``Option``: ``None``, or ``Some`` of a value of ``value`` (Effect's
    ``Option``). Anything else is ``Expected Option``."""
    return OptionSchema(
        _node(
            (value,),
            _option_run,
            "Option",
            lambda ps: option_link(*ps),
            to_equivalence=_inst.option_equivalence,
            to_formatter=_inst.option_formatter,
        ),
        value,
    )

Redacted

Redacted[A, I, RD, RE](value, /, *, label=None, disallow_json_encode=False) -> RedactedSchema[A, I, RD, RE]

A Redacted holding a value value (Effect's Redacted). An invalid value is reported as Expected a valid value at ["value"], never with its own message (that would show it); with a label, a secret labelled otherwise is Expected "<label>" at ["label"]. The parsed secret keeps the input's label. With disallow_json_encode its JSON codec refuses to write the secret (Cannot serialize Redacted).

ParameterTypeDescription
valueCodec[A, I, RD, RE]
labelstr | None = None
disallow_json_encodebool = False

Returns RedactedSchema[A, I, RD, RE]

def Redacted[A, I, RD, RE](
    value: Codec[A, I, RD, RE],
    /,
    *,
    label: str | None = None,
    disallow_json_encode: bool = False,
) -> RedactedSchema[A, I, RD, RE]:
    """A ``Redacted`` holding a ``value`` value (Effect's ``Redacted``). An
    invalid value is reported as ``Expected a valid value`` at
    ``["value"]``, never with its own message (that would show it); with a
    ``label``, a secret labelled otherwise is ``Expected "<label>"`` at
    ``["label"]``. The parsed secret keeps the input's label. With
    ``disallow_json_encode`` its JSON codec refuses to write the secret
    (``Cannot serialize Redacted``)."""
    payload: dict[str, object] = {}
    if label is not None:
        payload["label"] = label
    if disallow_json_encode:
        payload["disallowJsonEncode"] = True
    node = _node(
        (value,),
        _redacted_run(label),
        "Redacted",
        lambda ps: redacted_link(ps[0], label, disallow_encode=disallow_json_encode),
        to_equivalence=_inst.redacted_equivalence,
        to_formatter=_format_redacted,
        payload=payload or None,
    )
    return RedactedSchema(node, value, label)

Result

Result[A, E, AI, EI, RD, RE](success, failure) -> ResultSchema[A, E, AI, EI, RD, RE]

A Result: Ok of a success value, Err of a failure one (Effect's Result; issues at ["success"] / ["failure"]).

ParameterTypeDescription
successCodec[A, AI, RD, RE]
failureCodec[E, EI, RD, RE]

Returns ResultSchema[A, E, AI, EI, RD, RE]

def Result[A, E, AI, EI, RD, RE](
    success: Codec[A, AI, RD, RE], failure: Codec[E, EI, RD, RE], /
) -> ResultSchema[A, E, AI, EI, RD, RE]:
    """A ``Result``: ``Ok`` of a ``success`` value, ``Err`` of a ``failure``
    one (Effect's ``Result``; issues at ``["success"]`` / ``["failure"]``)."""
    return ResultSchema(
        _node(
            (success, failure),
            _result_run,
            "Result",
            lambda ps: result_link(*ps),
            to_equivalence=_inst.result_equivalence,
            to_formatter=_inst.result_formatter,
        ),
        success,
        failure,
    )

declare

declare[T](guard, **annotations) -> Bottom[T]

The values guard accepts, unchanged (Effect's declare); anything else is Expected <expected>, the expected annotation (default <Declaration>).

ParameterTypeDescription
guardCallable[[object], TypeIs[T]]
annotationsobject = {}

Returns Bottom[T]

def declare[T](guard: Callable[[object], TypeIs[T]], /, **annotations: object) -> Bottom[T]:
    """The values ``guard`` accepts, unchanged (Effect's ``declare``);
    anything else is ``Expected <expected>``, the ``expected`` annotation
    (default ``<Declaration>``)."""

    def run(_: tuple[ast.AST, ...]) -> Parse:
        def parse(
            input: object, node: ast.Declaration, options: ParseOptions
        ) -> Exit[object, Issue]:
            return Success(input) if guard(input) else ast.invalid_type(node, input, options)

        return parse

    return Bottom(ast.Declaration((), run, annotations=annotations or None))

declare_constructor

declare_constructor[T, RD, RE](type_parameters, run, **annotations) -> Bottom[T, Any, RD, RE]

A schema of a container of type_parameters' values (Effect's declareConstructor). run gets the type parameters' schemas (flipped when encoding) and returns the parser; it parses a part with schema.ast.parse(part, options) and reports its issue with ast.parse_at_key. The Type is what the parser returns; write the Encoded type out (Python cannot compute it from the type parameters): boxes: S.Bottom[Box[int], Box[str]] = S.declare_constructor(...).

ParameterTypeDescription
type_parametersSequence[Codec[Any, Any, RD, RE]]
runCallable[[tuple[Bottom[Any, Any, Never, Never], ...]], Parse[T]]
annotationsobject = {}

Returns Bottom[T, Any, RD, RE]

def declare_constructor[T, RD, RE](
    type_parameters: Sequence[Codec[Any, Any, RD, RE]],
    run: Callable[[tuple[Bottom[Any, Any, Never, Never], ...]], Parse[T]],
    /,
    **annotations: object,
) -> Bottom[T, Any, RD, RE]:
    """A schema of a container of ``type_parameters``' values (Effect's
    ``declareConstructor``). ``run`` gets the type parameters' schemas
    (flipped when encoding) and returns the parser; it parses a part with
    ``schema.ast.parse(part, options)`` and reports its issue with
    ``ast.parse_at_key``. The Type is what the parser returns; write the
    Encoded type out (Python cannot compute it from the type parameters):
    ``boxes: S.Bottom[Box[int], Box[str]] = S.declare_constructor(...)``."""

    def make_parser(nodes: tuple[ast.AST, ...]) -> Parse[T]:
        return run(tuple(Bottom(node) for node in nodes))

    nodes = tuple(p.__codec__().ast for p in type_parameters)
    return Bottom(ast.Declaration(nodes, make_parser, annotations=annotations or None))

instance_of

instance_of[T](cls, **annotations) -> Bottom[T]

Instances of cls (Effect's instanceOf), expected as the class name unless annotated.

ParameterTypeDescription
clstype[T]
annotationsobject = {}

Returns Bottom[T]

def instance_of[T](cls: type[T], /, **annotations: object) -> Bottom[T]:
    """Instances of ``cls`` (Effect's ``instanceOf``), expected as the class
    name unless annotated."""

    def guard(input: object) -> TypeIs[T]:
        return isinstance(input, cls)

    return declare(guard, **{"expected": cls.__name__, **annotations})

compile_ecma

compile_ecma(source, flags='u') -> re.Pattern[str]

source compiled as new RegExp(source, flags) reads it; raises EcmaPatternError. Without u the pattern matches code units (ecma_tester converts the input).

ParameterTypeDescription
sourcestr
flagsstr = 'u'

Returns re.Pattern[str]

@lru_cache(maxsize=256)
def compile_ecma(source: str, flags: str = "u") -> re.Pattern[str]:
    """``source`` compiled as ``new RegExp(source, flags)`` reads it; raises
    ``EcmaPatternError``. Without ``u`` the pattern matches code units
    (``ecma_tester`` converts the input)."""
    mode = _mode(flags)
    try:
        return re.compile(translate(source, mode), re.IGNORECASE if mode.ignore_case else re.ASCII)
    except (re.error, EcmaPatternError) as error:
        return _compile_on_regex(source, mode, error)

is_ecma_pattern

is_ecma_pattern(source, flags='u', **annotations) -> Filter[str]

A string the ECMAScript pattern new RegExp(source, flags) matches (Effect's isPattern; Unicode mode, /source/u, by default). JSON Schema's pattern holds these: this check writes one back when the flags are u with only d, g or y (sticky anchors it), as Effect's does. Raises EcmaPatternError for a pattern or flags that do not compile (v, and i without u, are refused).

ParameterTypeDescription
sourcestr
flagsstr = 'u'
annotationsobject = {}

Returns Filter[str]

def is_ecma_pattern(source: str, flags: str = "u", /, **annotations: object) -> Filter[str]:
    """A string the ECMAScript pattern ``new RegExp(source, flags)`` matches
    (Effect's ``isPattern``; Unicode mode, ``/source/u``, by default). JSON
    Schema's ``pattern`` holds these: this check writes one back when the
    flags are ``u`` with only ``d``, ``g`` or ``y`` (sticky anchors it), as
    Effect's does. Raises ``EcmaPatternError`` for a pattern or flags that
    do not compile (``v``, and ``i`` without ``u``, are refused)."""
    test = ecma_tester(source, flags)
    canonical = canonical_source(source)
    return string_filter(
        test,
        f"a string matching the RegExp {canonical}",
        "isPattern",
        {"source": canonical, "flags": _mode(flags).flags},
        annotations,
    )

Defect

Defect(*, include_stack=False, exclude_cause=False) -> DefectSchema

A defect in JSON (Effect's Defect()), for a Cause or Exit crossing a JSON boundary: an exception is written as an error (see ErrorInstance), anything else as JSON or its text; a JSON object with a string message decodes to an ErrorInstance, any other JSON value to itself. The same options give the same schema.

ParameterTypeDescription
include_stackbool = False
exclude_causebool = False

Returns DefectSchema

def Defect(*, include_stack: bool = False, exclude_cause: bool = False) -> DefectSchema:
    """A defect in JSON (Effect's ``Defect()``), for a ``Cause`` or ``Exit``
    crossing a JSON boundary: an exception is written as an error (see
    ``ErrorInstance``), anything else as JSON or its text; a JSON object with
    a string ``message`` decodes to an ``ErrorInstance``, any other JSON
    value to itself. The same options give the same schema."""
    return _defect_schema(include_stack, exclude_cause)

Graph

Graph[N, E, NI, EI, K: Kind, RD, RE](kind, node, edge) -> GraphSchema[N, E, NI, EI, K, RD, RE]

Immutable kind graphs ("directed" / "undirected") of node and edge payloads (Effect's Schema.Graph). A mutable graph or one of the other kind is Expected an immutable <kind> Graph. JSON writes the graph's snapshot, indexes kept.

ParameterTypeDescription
kindK
nodeCodec[N, NI, RD, RE]
edgeCodec[E, EI, RD, RE]

Returns GraphSchema[N, E, NI, EI, K, RD, RE]

def Graph[N, E, NI, EI, K: Kind, RD, RE](
    kind: K, node: Codec[N, NI, RD, RE], edge: Codec[E, EI, RD, RE], /
) -> GraphSchema[N, E, NI, EI, K, RD, RE]:
    """Immutable ``kind`` graphs (``"directed"`` / ``"undirected"``) of
    ``node`` and ``edge`` payloads (Effect's ``Schema.Graph``). A mutable
    graph or one of the other kind is ``Expected an immutable <kind>
    Graph``. JSON writes the graph's snapshot, indexes kept."""
    nodes = (node.__codec__().ast, edge.__codec__().ast)
    annotations = {
        "representation": {"id": "effect/schema/Graph", "payload": kind},
        "expected": f"an immutable {kind} Graph",
        "to_codec": _codec(kind),
        "to_codec_arbitrary": _arbitrary(kind),
        "to_equivalence": _equivalence,
    }
    declaration = ast.Declaration(nodes, _run(kind), annotations=annotations)
    return GraphSchema(declaration, kind, node, edge)

HashMap

HashMap[K, V, KI, VI, RD, RE](key, value) -> HashMapSchema[K, V, KI, VI, RD, RE]

A pyfect.hash_map.HashMap of key values to value values (Effect's Schema.HashMap), keyed by Effect's Equal: 1 and True are two keys. Anything else is Expected HashMap. JSON writes an array of [key, value] pairs.

ParameterTypeDescription
keyCodec[K, KI, RD, RE]
valueCodec[V, VI, RD, RE]

Returns HashMapSchema[K, V, KI, VI, RD, RE]

def HashMap[K, V, KI, VI, RD, RE](
    key: Codec[K, KI, RD, RE], value: Codec[V, VI, RD, RE], /
) -> HashMapSchema[K, V, KI, VI, RD, RE]:
    """A ``pyfect.hash_map.HashMap`` of ``key`` values to ``value`` values
    (Effect's ``Schema.HashMap``), keyed by Effect's ``Equal``: ``1`` and
    ``True`` are two keys. Anything else is ``Expected HashMap``. JSON
    writes an array of ``[key, value]`` pairs."""
    nodes = (key.__codec__().ast, value.__codec__().ast)
    annotations = {
        "representation": {"id": "effect/schema/HashMap", "payload": None},
        "expected": "HashMap",
        "to_codec": _map_codec,
        "to_codec_arbitrary": _map_arbitrary,
        "to_equivalence": _map_equivalence,
        "to_formatter": _map_formatter,
    }
    node = ast.Declaration(nodes, _map_run, annotations=annotations)
    return HashMapSchema(node, key, value)

HashSet

HashSet[A, I, RD, RE](value) -> HashSetSchema[A, I, RD, RE]

A pyfect.hash_set.HashSet of value's values (Effect's Schema.HashSet), keyed by Effect's Equal: 1 and True are two items. Anything else is Expected HashSet. JSON writes an array of the values.

ParameterTypeDescription
valueCodec[A, I, RD, RE]

Returns HashSetSchema[A, I, RD, RE]

def HashSet[A, I, RD, RE](value: Codec[A, I, RD, RE], /) -> HashSetSchema[A, I, RD, RE]:
    """A ``pyfect.hash_set.HashSet`` of ``value``'s values (Effect's
    ``Schema.HashSet``), keyed by Effect's ``Equal``: ``1`` and ``True``
    are two items. Anything else is ``Expected HashSet``. JSON writes an
    array of the values."""
    node = ast.Declaration(
        (value.__codec__().ast,),
        _set_run,
        annotations={
            "representation": {"id": "effect/schema/HashSet", "payload": None},
            "expected": "HashSet",
            "to_codec": _set_codec,
            "to_codec_arbitrary": _set_arbitrary,
            "to_equivalence": _set_equivalence,
            "to_formatter": _set_formatter,
        },
    )
    return HashSetSchema(node, value)

to_json_schema_document

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

The JSON Schema of schema's canonical JSON form, with its definitions apart (see to_json_schema_multi_document for the options).

ParameterTypeDescription
schemaTop
on_excess_propertyOnExcessProperty = 'ignore'
generate_descriptionsbool = False
include_annotation_keyCallable[[str], bool] | None = None
reference_policyReferencePolicy | None = None

Returns Document[Draft2020]

def to_json_schema_document(
    schema: Top,
    /,
    *,
    on_excess_property: OnExcessProperty = "ignore",
    generate_descriptions: bool = False,
    include_annotation_key: Callable[[str], bool] | None = None,
    reference_policy: ReferencePolicy | None = None,
) -> Document[Draft2020]:
    """The JSON Schema of ``schema``'s canonical JSON form, with its
    definitions apart (see ``to_json_schema_multi_document`` for the
    options)."""
    multi = to_json_schema_multi_document(
        (schema,),
        on_excess_property=on_excess_property,
        generate_descriptions=generate_descriptions,
        include_annotation_key=include_annotation_key,
        reference_policy=reference_policy,
    )
    return Document("draft-2020-12", multi.schemas[0], multi.definitions)

to_json_schema_multi_document

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

The JSON Schemas of several schemas, sharing their definitions.

on_excess_property="error" closes objects to keys the schema does not model (as the decoder option of that name does); generate_descriptions describes a check without a description by its expected text; include_annotation_key(key) admits other annotations with JSON values ("x-..."); reference_policy decides which nodes become definitions (default: those with an identifier).

ParameterTypeDescription
schemastuple[Top, *(tuple[Top, ...])]
on_excess_propertyOnExcessProperty = 'ignore'
generate_descriptionsbool = False
include_annotation_keyCallable[[str], bool] | None = None
reference_policyReferencePolicy | None = None

Returns MultiDocument[Draft2020]

def to_json_schema_multi_document(
    schemas: tuple[Top, *tuple[Top, ...]],
    /,
    *,
    on_excess_property: OnExcessProperty = "ignore",
    generate_descriptions: bool = False,
    include_annotation_key: Callable[[str], bool] | None = None,
    reference_policy: ReferencePolicy | None = None,
) -> MultiDocument[Draft2020]:
    """The JSON Schemas of several schemas, sharing their definitions.

    ``on_excess_property="error"`` closes objects to keys the schema does
    not model (as the decoder option of that name does);
    ``generate_descriptions`` describes a check without a ``description``
    by its ``expected`` text; ``include_annotation_key(key)`` admits other
    annotations with JSON values (``"x-..."``); ``reference_policy`` decides
    which nodes become definitions (default: those with an
    ``identifier``)."""
    nodes = to_codec_json_asts([schema.__codec__().ast for schema in schemas])
    references = References(nodes, reference_policy)
    compiler = Compiler(
        references,
        Options(on_excess_property, generate_descriptions, include_annotation_key),
    )
    roots = [compiler.recur(node, []) for node in nodes]
    out, definitions = compiler.finish(roots)
    return MultiDocument("draft-2020-12", tuple(out), definitions)

Enum

Enum[E: enum.Enum](enums) -> EnumSchema[E]

Decodes a value of enums (or a member) to its member and encodes a member to its value (Effect's Enum, whose members are their values). Values must be strings or finite numbers, else TypeError / ValueError.

ParameterTypeDescription
enumstype[E]

Returns EnumSchema[E]

def Enum[E: enum.Enum](enums: type[E], /) -> EnumSchema[E]:
    """Decodes a value of ``enums`` (or a member) to its member and encodes
    a member to its value (Effect's ``Enum``, whose members are their
    values). Values must be strings or finite numbers, else ``TypeError`` /
    ``ValueError``."""
    return EnumSchema(ast.Enum(enums), enums)

Literal

Literal[L: LiteralValue](literal) -> LiteralSchema[L]

Accepts literal only (a value of its kind: 1 is not True nor 1.0). A non-finite number raises ValueError.

ParameterTypeDescription
literalL

Returns LiteralSchema[L]

def Literal[L: LiteralValue](literal: L, /) -> LiteralSchema[L]:
    """Accepts ``literal`` only (a value of its kind: ``1`` is not ``True``
    nor ``1.0``). A non-finite number raises ``ValueError``."""
    return LiteralSchema(ast.Literal(literal), literal)

Literals

Literals[L: LiteralValue](literals: list[L] | tuple[L, ...], /) -> LiteralsSchema[L]
Literals[L: LiteralValue](*literals: L = ()) -> LiteralsSchema[L]

Accepts any of literals (Effect's Literals, a union of Literal members): Expected "a" | "b" otherwise. The literals are given as arguments or, as in Effect, as one list or tuple.

ParameterTypeDescription
literals= ()
@overload
def Literals[L: LiteralValue](literals: list[L] | tuple[L, ...], /) -> LiteralsSchema[L]: ...
@overload
def Literals[L: LiteralValue](*literals: L) -> LiteralsSchema[L]: ...
def Literals(*literals: Any) -> LiteralsSchema[Any]:
    """Accepts any of ``literals`` (Effect's ``Literals``, a union of
    ``Literal`` members): ``Expected "a" | "b"`` otherwise. The literals are
    given as arguments or, as in Effect, as one list or tuple."""
    literals = one_or_many(literals)
    return LiteralsSchema(ast.Union(tuple(ast.Literal(lit) for lit in literals)), literals)

Union

Union[A = Never, I = Never, RD = Never, RE = Never](members: list[Codec[A, I, RD, RE]] | tuple[Codec[A, I, RD, RE], ...], /, *, mode: ast.UnionMode = 'any_of') -> UnionSchema[A, I, RD, RE]
Union[A = Never, I = Never, RD = Never, RE = Never](*members: Codec[A, I, RD, RE] = (), mode: ast.UnionMode = 'any_of') -> UnionSchema[A, I, RD, RE]

A value of any member, tried in order (mode="one_of": of exactly one, failing when several match). The members are given as arguments or, as in Effect, as one list or tuple.

ParameterTypeDescription
members= ()
mode= 'any_of'
@overload
def Union[A = Never, I = Never, RD = Never, RE = Never](
    members: list[Codec[A, I, RD, RE]] | tuple[Codec[A, I, RD, RE], ...],
    /,
    *,
    mode: ast.UnionMode = "any_of",
) -> UnionSchema[A, I, RD, RE]: ...
@overload
def Union[A = Never, I = Never, RD = Never, RE = Never](
    *members: Codec[A, I, RD, RE], mode: ast.UnionMode = "any_of"
) -> UnionSchema[A, I, RD, RE]: ...
def Union(*members: Any, mode: ast.UnionMode = "any_of") -> UnionSchema[Any, Any, Any, Any]:
    """A value of any member, tried in order (``mode="one_of"``: of exactly
    one, failing when several match). The members are given as arguments
    or, as in Effect, as one list or tuple."""
    members = one_or_many(members)
    node = ast.Union(tuple(m.__codec__().ast for m in members), mode)
    return UnionSchema(node, members)

make_class_sync

make_class_sync[T](ast, input, options, construct) -> T

A class instance made from its type side (Effect's SchemaParser.makeClassSync): an installed make / make_effect makes it; otherwise an instance is kept as it is, and plain fields are checked by the fields' constructor (resolved through the class's entry) and handed to construct, a raise there being a constructor defect; the class's own checks then run on the instance.

ParameterTypeDescription
astAST
inputobject
optionsParseOptions | None
constructCallable[[Mapping[object, object]], T]

Returns T

def make_class_sync[T](
    ast: AST,
    input: object,
    options: ParseOptions | None,
    construct: Callable[[Mapping[object, object]], T],
) -> T:
    """A class instance made from its type side (Effect's ``SchemaParser.makeClassSync``):
    an installed ``make`` / ``make_effect`` makes it; otherwise an instance is kept as it
    is, and plain fields are checked by the fields' constructor (resolved through the
    class's entry) and handed to ``construct``, a raise there being a constructor defect;
    the class's own checks then run on the instance."""
    entry = _registry.resolve(ast)
    plain = options or DEFAULT_PARSE_OPTIONS
    if (
        not isinstance(ast, Class)
        or entry.make is not None
        or entry.compiled_make_effect is not None
    ):
        return cast("T", _construct_sync(entry, input, plain))
    shape = ast.shape
    if isinstance(input, shape.cls):
        return cast("T", input)
    fields = _construct_sync(entry.resolve(shape.fields.to_type()), input, plain)
    try:
        instance = construct(cast("Mapping[object, object]", fields))
    except Exception as defect:
        _constructor_defect(defect)
    match check_instance(shape, instance, plain):
        case Success():
            return instance
        case failure:
            raise_schema_failure(failure.cause.map(SchemaError), CONSTRUCTOR)

catch_decoding

catch_decoding[T, R = Never](f) -> CatchDecoding[T, R]

A failed decoding replaced by f(issue): Some(value), None (no value: a missing key), or another failure (Effect's catchDecoding / catchDecodingWithContext; f may need services).

ParameterTypeDescription
fCallable[[Issue], Parse[T, R]]

Returns CatchDecoding[T, R]

def catch_decoding[T, R = Never](f: Callable[[Issue], Parse[T, R]], /) -> CatchDecoding[T, R]:
    """A failed decoding replaced by ``f(issue)``: ``Some(value)``, ``None``
    (no value: a missing key), or another failure (Effect's
    ``catchDecoding`` / ``catchDecodingWithContext``; ``f`` may need
    services)."""
    return CatchDecoding(f)

catch_encoding

catch_encoding[E, R = Never](f) -> CatchEncoding[E, R]

A failed encoding replaced by f(issue) (Effect's catchEncoding / catchEncodingWithContext).

ParameterTypeDescription
fCallable[[Issue], Parse[E, R]]

Returns CatchEncoding[E, R]

def catch_encoding[E, R = Never](f: Callable[[Issue], Parse[E, R]], /) -> CatchEncoding[E, R]:
    """A failed encoding replaced by ``f(issue)`` (Effect's ``catchEncoding``
    / ``catchEncodingWithContext``)."""
    return CatchEncoding(f)

middleware_decoding

middleware_decoding[T, RI = Never, R = Never](f) -> MiddlewareDecoding[T, RI, R]

The schema's decoding passed through f(parse, options): the schema then decodes with the services f needs (Effect's middlewareDecoding).

ParameterTypeDescription
fCallable[[Parse[T, RI], ParseOptions], Parse[T, R]]

Returns MiddlewareDecoding[T, RI, R]

def middleware_decoding[T, RI = Never, R = Never](
    f: Callable[[Parse[T, RI], ParseOptions], Parse[T, R]], /
) -> MiddlewareDecoding[T, RI, R]:
    """The schema's decoding passed through ``f(parse, options)``: the
    schema then decodes with the services ``f`` needs (Effect's
    ``middlewareDecoding``)."""
    return MiddlewareDecoding(f)

middleware_encoding

middleware_encoding[E, RI = Never, R = Never](f) -> MiddlewareEncoding[E, RI, R]

The schema's encoding passed through f(parse, options): the schema then encodes with the services f needs (Effect's middlewareEncoding).

ParameterTypeDescription
fCallable[[Parse[E, RI], ParseOptions], Parse[E, R]]

Returns MiddlewareEncoding[E, RI, R]

def middleware_encoding[E, RI = Never, R = Never](
    f: Callable[[Parse[E, RI], ParseOptions], Parse[E, R]], /
) -> MiddlewareEncoding[E, RI, R]:
    """The schema's encoding passed through ``f(parse, options)``: the
    schema then encodes with the services ``f`` needs (Effect's
    ``middlewareEncoding``)."""
    return MiddlewareEncoding(f)

with_decoding_default

with_decoding_default[E, R = Never](default, /, *, encoding_strategy='passthrough') -> WithDecodingDefault[E, R]

A missing struct key or None decoded as default's Encoded value (Effect's withDecodingDefault, None standing for undefined): the key is optional and nullable on the encoded side; encoding_strategy="omit" leaves it out when encoding.

ParameterTypeDescription
defaultEffect[E, SchemaError, R]
encoding_strategyEncodingStrategy = 'passthrough'

Returns WithDecodingDefault[E, R]

def with_decoding_default[E, R = Never](
    default: Effect[E, SchemaError, R], /, *, encoding_strategy: EncodingStrategy = "passthrough"
) -> WithDecodingDefault[E, R]:
    """A missing struct key or ``None`` decoded as ``default``'s Encoded
    value (Effect's ``withDecodingDefault``, ``None`` standing for
    ``undefined``): the key is optional and nullable on the encoded side;
    ``encoding_strategy="omit"`` leaves it out when encoding."""
    require_effect(default, "default")
    return WithDecodingDefault(default, encoding_strategy)

with_decoding_default_key

with_decoding_default_key[E, R = Never](default, /, *, encoding_strategy='passthrough') -> WithDecodingDefaultKey[E, R]

A missing struct key decoded as default's Encoded value (Effect's withDecodingDefaultKey): the key is optional on the encoded side; encoding_strategy="omit" leaves it out when encoding.

ParameterTypeDescription
defaultEffect[E, SchemaError, R]
encoding_strategyEncodingStrategy = 'passthrough'

Returns WithDecodingDefaultKey[E, R]

def with_decoding_default_key[E, R = Never](
    default: Effect[E, SchemaError, R], /, *, encoding_strategy: EncodingStrategy = "passthrough"
) -> WithDecodingDefaultKey[E, R]:
    """A missing struct key decoded as ``default``'s Encoded value (Effect's
    ``withDecodingDefaultKey``): the key is optional on the encoded side;
    ``encoding_strategy="omit"`` leaves it out when encoding."""
    require_effect(default, "default")
    return WithDecodingDefaultKey(default, encoding_strategy)

with_decoding_default_type

with_decoding_default_type[T, R = Never](default, /, *, encoding_strategy='passthrough') -> WithDecodingDefaultType[T, R]

A missing struct key or None decoded as default's Type value (Effect's withDecodingDefaultType).

ParameterTypeDescription
defaultEffect[T, SchemaError, R]
encoding_strategyEncodingStrategy = 'passthrough'

Returns WithDecodingDefaultType[T, R]

def with_decoding_default_type[T, R = Never](
    default: Effect[T, SchemaError, R], /, *, encoding_strategy: EncodingStrategy = "passthrough"
) -> WithDecodingDefaultType[T, R]:
    """A missing struct key or ``None`` decoded as ``default``'s Type value
    (Effect's ``withDecodingDefaultType``)."""
    require_effect(default, "default")
    return WithDecodingDefaultType(default, encoding_strategy)

with_decoding_default_type_key

with_decoding_default_type_key[T, R = Never](default, /, *, encoding_strategy='passthrough') -> WithDecodingDefaultTypeKey[T, R]

A missing struct key decoded as default's Type value (Effect's withDecodingDefaultTypeKey).

ParameterTypeDescription
defaultEffect[T, SchemaError, R]
encoding_strategyEncodingStrategy = 'passthrough'

Returns WithDecodingDefaultTypeKey[T, R]

def with_decoding_default_type_key[T, R = Never](
    default: Effect[T, SchemaError, R], /, *, encoding_strategy: EncodingStrategy = "passthrough"
) -> WithDecodingDefaultTypeKey[T, R]:
    """A missing struct key decoded as ``default``'s Type value (Effect's
    ``withDecodingDefaultTypeKey``)."""
    require_effect(default, "default")
    return WithDecodingDefaultTypeKey(default, encoding_strategy)

asserts

asserts(schema, input) -> None

Raise SchemaError unless input is a value of the schema's decoded side.

ParameterTypeDescription
schemaTop
inputobject
def asserts(schema: Top, input: object, /) -> None:
    """Raise ``SchemaError`` unless ``input`` is a value of the schema's
    decoded side."""
    run: _Run[object] = _runner(schema.__codec__().ast.to_type(), {})
    match _run_now(run, input, {}):
        case Success():
            return
        case failure:
            raise_schema_failure(failure.cause, ASSERTION)

decode_effect

decode_effect[A, I, R](schema, **options) -> Parser[I, Effect[A, SchemaError, R]]
ParameterTypeDescription
schemaCodec[A, I, R, object]
optionsUnpack[ParseOptions] = {}

Returns Parser[I, Effect[A, SchemaError, R]]

def decode_effect[A, I, R](
    schema: Codec[A, I, R, object], /, **options: Unpack[ParseOptions]
) -> Parser[I, Effect[A, SchemaError, R]]:
    return _as_effect(_decoding(schema, options))

decode_exit

decode_exit[A, I](schema, **options) -> Parser[I, Exit[A, SchemaError]]
ParameterTypeDescription
schemaCodec[A, I, Never, object]
optionsUnpack[ParseOptions] = {}

Returns Parser[I, Exit[A, SchemaError]]

def decode_exit[A, I](
    schema: Codec[A, I, Never, object], /, **options: Unpack[ParseOptions]
) -> Parser[I, Exit[A, SchemaError]]:
    return _as_exit(_decoding(schema, options))

decode_option

decode_option[A, I](schema, **options) -> Parser[I, Option[A]]
ParameterTypeDescription
schemaCodec[A, I, Never, object]
optionsUnpack[ParseOptions] = {}

Returns Parser[I, Option[A]]

def decode_option[A, I](
    schema: Codec[A, I, Never, object], /, **options: Unpack[ParseOptions]
) -> Parser[I, Option[A]]:
    return _as_option(_decoding(schema, options))

decode_promise

decode_promise[A, I](schema, **options) -> Parser[I, Coroutine[Any, Any, A]]

A coroutine that decodes, raising SchemaError (Effect's decodePromise).

ParameterTypeDescription
schemaCodec[A, I, Never, object]
optionsUnpack[ParseOptions] = {}

Returns Parser[I, Coroutine[Any, Any, A]]

def decode_promise[A, I](
    schema: Codec[A, I, Never, object], /, **options: Unpack[ParseOptions]
) -> Parser[I, Coroutine[Any, Any, A]]:
    """A coroutine that decodes, raising ``SchemaError`` (Effect's
    ``decodePromise``)."""
    return _as_promise(decode_effect(schema, **options))

decode_result

decode_result[A, I](schema, **options) -> Parser[I, Result[A, SchemaError]]
ParameterTypeDescription
schemaCodec[A, I, Never, object]
optionsUnpack[ParseOptions] = {}

Returns Parser[I, Result[A, SchemaError]]

def decode_result[A, I](
    schema: Codec[A, I, Never, object], /, **options: Unpack[ParseOptions]
) -> Parser[I, Result[A, SchemaError]]:
    return _as_result(_decoding(schema, options))

decode_sync

decode_sync[A, I](schema, **options) -> Parser[I, A]
ParameterTypeDescription
schemaCodec[A, I, Never, object]
optionsUnpack[ParseOptions] = {}

Returns Parser[I, A]

def decode_sync[A, I](
    schema: Codec[A, I, Never, object], /, **options: Unpack[ParseOptions]
) -> Parser[I, A]:
    return _as_sync(_decoding(schema, options))

decode_unknown_effect

decode_unknown_effect[A, R](schema, **options) -> Parser[object, Effect[A, SchemaError, R]]
ParameterTypeDescription
schemaCodec[A, object, R, object]
optionsUnpack[ParseOptions] = {}

Returns Parser[object, Effect[A, SchemaError, R]]

def decode_unknown_effect[A, R](
    schema: Codec[A, object, R, object], /, **options: Unpack[ParseOptions]
) -> Parser[object, Effect[A, SchemaError, R]]:
    return _as_effect(_decoding(schema, options))

decode_unknown_exit

decode_unknown_exit[A](schema, **options) -> Parser[object, Exit[A, SchemaError]]
ParameterTypeDescription
schemaCodec[A, object, Never, object]
optionsUnpack[ParseOptions] = {}

Returns Parser[object, Exit[A, SchemaError]]

def decode_unknown_exit[A](
    schema: Codec[A, object, Never, object], /, **options: Unpack[ParseOptions]
) -> Parser[object, Exit[A, SchemaError]]:
    return _as_exit(_decoding(schema, options))

decode_unknown_option

decode_unknown_option[A](schema, **options) -> Parser[object, Option[A]]
ParameterTypeDescription
schemaCodec[A, object, Never, object]
optionsUnpack[ParseOptions] = {}

Returns Parser[object, Option[A]]

def decode_unknown_option[A](
    schema: Codec[A, object, Never, object], /, **options: Unpack[ParseOptions]
) -> Parser[object, Option[A]]:
    return _as_option(_decoding(schema, options))

decode_unknown_promise

decode_unknown_promise[A](schema, **options) -> Parser[object, Coroutine[Any, Any, A]]

A coroutine that decodes, raising SchemaError (Effect's decodeUnknownPromise).

ParameterTypeDescription
schemaCodec[A, object, Never, object]
optionsUnpack[ParseOptions] = {}

Returns Parser[object, Coroutine[Any, Any, A]]

def decode_unknown_promise[A](
    schema: Codec[A, object, Never, object], /, **options: Unpack[ParseOptions]
) -> Parser[object, Coroutine[Any, Any, A]]:
    """A coroutine that decodes, raising ``SchemaError`` (Effect's
    ``decodeUnknownPromise``)."""
    return _as_promise(decode_unknown_effect(schema, **options))

decode_unknown_result

decode_unknown_result[A](schema, **options) -> Parser[object, Result[A, SchemaError]]
ParameterTypeDescription
schemaCodec[A, object, Never, object]
optionsUnpack[ParseOptions] = {}

Returns Parser[object, Result[A, SchemaError]]

def decode_unknown_result[A](
    schema: Codec[A, object, Never, object], /, **options: Unpack[ParseOptions]
) -> Parser[object, Result[A, SchemaError]]:
    return _as_result(_decoding(schema, options))

decode_unknown_sync

decode_unknown_sync[A](schema, **options) -> Parser[object, A]
ParameterTypeDescription
schemaCodec[A, object, Never, object]
optionsUnpack[ParseOptions] = {}

Returns Parser[object, A]

def decode_unknown_sync[A](
    schema: Codec[A, object, Never, object], /, **options: Unpack[ParseOptions]
) -> Parser[object, A]:
    return _as_sync(_decoding(schema, options))

encode_effect

encode_effect[A, I, R](schema, **options) -> Parser[A, Effect[I, SchemaError, R]]
ParameterTypeDescription
schemaCodec[A, I, object, R]
optionsUnpack[ParseOptions] = {}

Returns Parser[A, Effect[I, SchemaError, R]]

def encode_effect[A, I, R](
    schema: Codec[A, I, object, R], /, **options: Unpack[ParseOptions]
) -> Parser[A, Effect[I, SchemaError, R]]:
    return _as_effect(_encoding(schema, options))

encode_exit

encode_exit[A, I](schema, **options) -> Parser[A, Exit[I, SchemaError]]
ParameterTypeDescription
schemaCodec[A, I, object, Never]
optionsUnpack[ParseOptions] = {}

Returns Parser[A, Exit[I, SchemaError]]

def encode_exit[A, I](
    schema: Codec[A, I, object, Never], /, **options: Unpack[ParseOptions]
) -> Parser[A, Exit[I, SchemaError]]:
    return _as_exit(_encoding(schema, options))

encode_option

encode_option[A, I](schema, **options) -> Parser[A, Option[I]]
ParameterTypeDescription
schemaCodec[A, I, object, Never]
optionsUnpack[ParseOptions] = {}

Returns Parser[A, Option[I]]

def encode_option[A, I](
    schema: Codec[A, I, object, Never], /, **options: Unpack[ParseOptions]
) -> Parser[A, Option[I]]:
    return _as_option(_encoding(schema, options))

encode_promise

encode_promise[A, I](schema, **options) -> Parser[A, Coroutine[Any, Any, I]]

A coroutine that encodes, raising SchemaError (Effect's encodePromise).

ParameterTypeDescription
schemaCodec[A, I, object, Never]
optionsUnpack[ParseOptions] = {}

Returns Parser[A, Coroutine[Any, Any, I]]

def encode_promise[A, I](
    schema: Codec[A, I, object, Never], /, **options: Unpack[ParseOptions]
) -> Parser[A, Coroutine[Any, Any, I]]:
    """A coroutine that encodes, raising ``SchemaError`` (Effect's
    ``encodePromise``)."""
    return _as_promise(encode_effect(schema, **options))

encode_result

encode_result[A, I](schema, **options) -> Parser[A, Result[I, SchemaError]]
ParameterTypeDescription
schemaCodec[A, I, object, Never]
optionsUnpack[ParseOptions] = {}

Returns Parser[A, Result[I, SchemaError]]

def encode_result[A, I](
    schema: Codec[A, I, object, Never], /, **options: Unpack[ParseOptions]
) -> Parser[A, Result[I, SchemaError]]:
    return _as_result(_encoding(schema, options))

encode_sync

encode_sync[A, I](schema, **options) -> Parser[A, I]
ParameterTypeDescription
schemaCodec[A, I, object, Never]
optionsUnpack[ParseOptions] = {}

Returns Parser[A, I]

def encode_sync[A, I](
    schema: Codec[A, I, object, Never], /, **options: Unpack[ParseOptions]
) -> Parser[A, I]:
    return _as_sync(_encoding(schema, options))

encode_unknown_effect

encode_unknown_effect[I, R](schema, **options) -> Parser[object, Effect[I, SchemaError, R]]
ParameterTypeDescription
schemaCodec[object, I, object, R]
optionsUnpack[ParseOptions] = {}

Returns Parser[object, Effect[I, SchemaError, R]]

def encode_unknown_effect[I, R](
    schema: Codec[object, I, object, R], /, **options: Unpack[ParseOptions]
) -> Parser[object, Effect[I, SchemaError, R]]:
    return _as_effect(_encoding(schema, options))

encode_unknown_exit

encode_unknown_exit[I](schema, **options) -> Parser[object, Exit[I, SchemaError]]
ParameterTypeDescription
schemaCodec[object, I, object, Never]
optionsUnpack[ParseOptions] = {}

Returns Parser[object, Exit[I, SchemaError]]

def encode_unknown_exit[I](
    schema: Codec[object, I, object, Never], /, **options: Unpack[ParseOptions]
) -> Parser[object, Exit[I, SchemaError]]:
    return _as_exit(_encoding(schema, options))

encode_unknown_option

encode_unknown_option[I](schema, **options) -> Parser[object, Option[I]]
ParameterTypeDescription
schemaCodec[object, I, object, Never]
optionsUnpack[ParseOptions] = {}

Returns Parser[object, Option[I]]

def encode_unknown_option[I](
    schema: Codec[object, I, object, Never], /, **options: Unpack[ParseOptions]
) -> Parser[object, Option[I]]:
    return _as_option(_encoding(schema, options))

encode_unknown_promise

encode_unknown_promise[I](schema, **options) -> Parser[object, Coroutine[Any, Any, I]]

A coroutine that encodes, raising SchemaError (Effect's encodeUnknownPromise).

ParameterTypeDescription
schemaCodec[object, I, object, Never]
optionsUnpack[ParseOptions] = {}

Returns Parser[object, Coroutine[Any, Any, I]]

def encode_unknown_promise[I](
    schema: Codec[object, I, object, Never], /, **options: Unpack[ParseOptions]
) -> Parser[object, Coroutine[Any, Any, I]]:
    """A coroutine that encodes, raising ``SchemaError`` (Effect's
    ``encodeUnknownPromise``)."""
    return _as_promise(encode_unknown_effect(schema, **options))

encode_unknown_result

encode_unknown_result[I](schema, **options) -> Parser[object, Result[I, SchemaError]]
ParameterTypeDescription
schemaCodec[object, I, object, Never]
optionsUnpack[ParseOptions] = {}

Returns Parser[object, Result[I, SchemaError]]

def encode_unknown_result[I](
    schema: Codec[object, I, object, Never], /, **options: Unpack[ParseOptions]
) -> Parser[object, Result[I, SchemaError]]:
    return _as_result(_encoding(schema, options))

encode_unknown_sync

encode_unknown_sync[I](schema, **options) -> Parser[object, I]
ParameterTypeDescription
schemaCodec[object, I, object, Never]
optionsUnpack[ParseOptions] = {}

Returns Parser[object, I]

def encode_unknown_sync[I](
    schema: Codec[object, I, object, Never], /, **options: Unpack[ParseOptions]
) -> Parser[object, I]:
    return _as_sync(_encoding(schema, options))

is_

is_[A](schema) -> Guard[A]

A type guard for the schema's decoded side (Effect's is): an installed is_ operation when there is one, called with DEFAULT_PARSE_OPTIONS.

ParameterTypeDescription
schemaCodec[A, object, object, object]

Returns Guard[A]

def is_[A](schema: Codec[A, object, object, object], /) -> Guard[A]:
    """A type guard for the schema's decoded side (Effect's ``is``): an
    installed ``is_`` operation when there is one, called with
    ``DEFAULT_PARSE_OPTIONS``."""
    ast = schema.__codec__().ast.to_type()
    resolved: list[Callable[[object], bool]] = []

    def guard(input: object, /) -> TypeIs[A]:
        if not resolved:
            # As in Effect, a guard first called before anything is
            # installed stays with the interpreter.
            active = _registry.active()
            run = _runner(ast, {})
            entry = _registry.resolve(ast)
            resolved.append(_guard_of(entry) if active else lambda input: _check(run, input))
        return resolved[0](input)

    return guard

make

make[A](schema) -> Parser[A, A]

The schema's constructor (Effect's SchemaParser.make): raises SchemaError. Its registry entry is resolved on the first call and kept.

ParameterTypeDescription
schemaCodec[A, object, object, object]

Returns Parser[A, A]

def make[A](schema: Codec[A, object, object, object], /) -> Parser[A, A]:
    """The schema's constructor (Effect's ``SchemaParser.make``): raises
    ``SchemaError``. Its registry entry is resolved on the first call and
    kept."""
    maker = Maker(schema.__codec__().ast.to_type())

    def construct(input: A, /, **options: Unpack[ParseOptions]) -> A:
        match run_now(maker.parse(input, options, True)):
            case Success(value):
                return cast("A", value)
            case failure:
                raise_schema_failure(failure.cause.map(SchemaError), CONSTRUCTOR)

    return construct

make_effect

make_effect[A](schema) -> Parser[A, Effect[A, Issue, Any]]

The schema's constructor as an effect failing with the bare Issue (Effect's SchemaParser.makeEffect).

ParameterTypeDescription
schemaCodec[A, object, object, object]

Returns Parser[A, Effect[A, Issue, Any]]

def make_effect[A](schema: Codec[A, object, object, object], /) -> Parser[A, Effect[A, Issue, Any]]:
    """The schema's constructor as an effect failing with the bare ``Issue``
    (Effect's ``SchemaParser.makeEffect``)."""
    maker = Maker(schema.__codec__().ast.to_type())

    def construct(input: A, /, **options: Unpack[ParseOptions]) -> Effect[A, Issue, Any]:
        return cast("Effect[A, Issue, Any]", to_effect(maker.parse(input, options, False)))

    return construct

make_option

make_option[A](schema) -> Parser[A, Option[A]]

The schema's constructor giving Some or None (Effect's SchemaParser.makeOption).

ParameterTypeDescription
schemaCodec[A, object, object, object]

Returns Parser[A, Option[A]]

def make_option[A](schema: Codec[A, object, object, object], /) -> Parser[A, Option[A]]:
    """The schema's constructor giving ``Some`` or ``None`` (Effect's
    ``SchemaParser.makeOption``)."""
    maker = Maker(schema.__codec__().ast.to_type())

    def construct(input: A, /, **options: Unpack[ParseOptions]) -> Option[A]:
        match run_now(maker.parse(input, options, True)):
            case Success(value):
                return Some(cast("A", value))
            case failure:
                schema_error_of(failure.cause.map(SchemaError), OPTION)
                return None

    return construct

Record

Record[K, V, KI, VI, RD, RE](key, value) -> RecordSchema[K, V, KI, VI, RD, RE]

A mapping whose keys key accepts, with values of value (Effect's Record). A literal key (S.Literal, S.Literals) is required; any other key schema takes the keys it accepts, its checks included, and the other keys are excess: dropped, or rejected under on_excess_property="error".

ParameterTypeDescription
keyCodec[K, KI, RD, RE]
valueCodec[V, VI, RD, RE]

Returns RecordSchema[K, V, KI, VI, RD, RE]

def Record[K, V, KI, VI, RD, RE](
    key: Codec[K, KI, RD, RE], value: Codec[V, VI, RD, RE], /
) -> RecordSchema[K, V, KI, VI, RD, RE]:
    """A mapping whose keys ``key`` accepts, with values of ``value``
    (Effect's ``Record``). A literal key (``S.Literal``, ``S.Literals``) is
    required; any other key schema takes the keys it accepts, its checks
    included, and the other keys are excess: dropped, or rejected under
    ``on_excess_property="error"``."""
    return RecordSchema(ast.record(key.__codec__().ast, value.__codec__().ast), key, value)

from_brand

from_brand[A, B](brand, /, *, identifier=None) -> FromBrand[A, B]

The schema's values branded as B, after brand's checks: S.Number.pipe(S.from_brand(Brand[float, Int].check(S.is_int()))). A nominal brand adds no check, so it is Effect's brand(identifier). The result keeps the schema it brands (.schema) and identifier (.identifier), as Effect's fromBrand.

ParameterTypeDescription
brandBrand[A, B]
identifierstr | None = None

Returns FromBrand[A, B]

def from_brand[A, B](brand: Brand[A, B], /, *, identifier: str | None = None) -> FromBrand[A, B]:
    """The schema's values branded as ``B``, after ``brand``'s checks:
    ``S.Number.pipe(S.from_brand(Brand[float, Int].check(S.is_int())))``.
    A nominal brand adds no check, so it is Effect's ``brand(identifier)``.
    The result keeps the schema it brands (``.schema``) and
    ``identifier`` (``.identifier``), as Effect's ``fromBrand``."""
    return FromBrand(brand, identifier)

make_filter_group

make_filter_group[T](first, *rest, **annotations) -> FilterGroup[T]

Several checks as one (Effect's makeFilterGroup).

ParameterTypeDescription
firstCheck[T]
restCheck[T] = ()
annotationsobject = {}

Returns FilterGroup[T]

def make_filter_group[T](
    first: Check[T], /, *rest: Check[T], **annotations: object
) -> FilterGroup[T]:
    """Several checks as one (Effect's ``makeFilterGroup``)."""
    return FilterGroup((first, *rest), annotations or None)

refine

refine[A, B](guard, **annotations) -> Refine[A, B]

Narrow a schema's type to what guard accepts, checking it as the last step; a value it rejects fails with "Expected <expected>" (expected= annotation, else <filter>) and stops the checks.

ParameterTypeDescription
guardCallable[[A], TypeIs[B]]
annotationsobject = {}

Returns Refine[A, B]

def refine[A, B](guard: Callable[[A], TypeIs[B]], /, **annotations: object) -> Refine[A, B]:
    """Narrow a schema's type to what ``guard`` accepts, checking it as the
    last step; a value it rejects fails with ``"Expected <expected>"``
    (``expected=`` annotation, else ``<filter>``) and stops the checks."""
    return Refine(make_filter_by_guard(guard, annotations or None))

resolve_annotations

resolve_annotations(schema) -> Annotations | None

The annotations describing schema: its last check's when it has checks, else its own; None without any.

ParameterTypeDescription
schemaTop

Returns Annotations | None

def resolve_annotations(schema: Top, /) -> Annotations | None:
    """The annotations describing ``schema``: its last check's when it has
    checks, else its own; ``None`` without any."""
    return schema.__codec__().ast.resolve()

resolve_annotations_key

resolve_annotations_key(schema) -> Annotations | None

The annotations of the struct key or tuple element holding schema (annotate_key); None without any (Effect's resolveAnnotationsKey).

ParameterTypeDescription
schemaTop

Returns Annotations | None

def resolve_annotations_key(schema: Top, /) -> Annotations | None:
    """The annotations of the struct key or tuple element holding
    ``schema`` (``annotate_key``); ``None`` without any (Effect's
    ``resolveAnnotationsKey``)."""
    return schema.__codec__().ast.key_annotations

is_schema

is_schema(value) -> TypeIs[Top]

value is a schema object, a schema class, or a schema adapted to Standard Schema.

ParameterTypeDescription
valueobject

Returns TypeIs[Top]

def is_schema(value: object) -> TypeIs[Top]:
    """``value`` is a schema object, a schema class, or a schema adapted to
    Standard Schema."""
    from pyfect.schema._standard_schema import StandardSchemaV1

    return isinstance(value, (Bottom, StandardSchemaV1)) or (
        isinstance(value, type) and hasattr(value, "__codec__")
    )

to_standard_json_schema_v1

to_standard_json_schema_v1[T, E, RD, RE](schema) -> StandardSchemaV1[T, E, RD, RE]

schema with a Standard JSON Schema converter (see the module).

ParameterTypeDescription
schemaCodec[T, E, RD, RE]

Returns StandardSchemaV1[T, E, RD, RE]

def to_standard_json_schema_v1[T, E, RD, RE](
    schema: Codec[T, E, RD, RE], /
) -> StandardSchemaV1[T, E, RD, RE]:
    """``schema`` with a Standard JSON Schema converter (see the module)."""
    target, props = _target_and_props(schema)
    return StandardSchemaV1(target, replace(props, json_schema=JsonSchemaConverter(target)))

to_standard_schema_v1

to_standard_schema_v1[T, E, RE](schema, /, *, leaf_hook=None, check_hook=None, parse_options=None) -> StandardSchemaV1[T, E, Never, RE]

schema with a Standard Schema validate (see the module).

ParameterTypeDescription
schemaCodec[T, E, Never, RE]
leaf_hookLeafHook | None = None
check_hookCheckHook | None = None
parse_optionsParseOptions | None = None

Returns StandardSchemaV1[T, E, Never, RE]

def to_standard_schema_v1[T, E, RE](
    schema: Codec[T, E, Never, RE],
    /,
    *,
    leaf_hook: LeafHook | None = None,
    check_hook: CheckHook | None = None,
    parse_options: ParseOptions | None = None,
) -> StandardSchemaV1[T, E, Never, RE]:
    """``schema`` with a Standard Schema ``validate`` (see the module)."""
    target, props = _target_and_props(schema)
    decode = decode_unknown_effect(cast("Codec[T, object, Never, object]", target))
    options: ParseOptions = {"errors": "all", **(parse_options or {})}
    formatter = make_formatter_standard_schema_v1(leaf_hook=leaf_hook, check_hook=check_hook)

    def validate(
        value: object, _options: ValidateOptions | None = None, /
    ) -> Result[T] | Awaitable[Result[T]]:
        effect = decode(value, **options).match(
            on_failure=lambda error: cast("Result[T]", formatter(error.issue)),
            on_success=lambda decoded: cast("Result[T]", {"value": decoded}),
        )
        return _run(effect)

    return StandardSchemaV1(target, replace(props, validate=validate))

Struct

Struct[TD: Mapping[str, object]](typed_dict: type[TD], /) -> StructSchema[TD, Never, Never]
Struct[TD: Mapping[str, object], RD, RE](typed_dict: type[TD], /, **fields: Codec[object, object, RD, RE] = {}) -> StructSchema[TD, RD, RE]

A mapping with the keys of typed_dict (Effect's Struct). Each key's schema comes from its annotation unless given here; a name the TypedDict lacks raises TypeError, as does an annotation with no schema (see pyfect.schema for which annotations have one).

ParameterTypeDescription
typed_dict
fields= {}
@overload
def Struct[TD: Mapping[str, object]](typed_dict: type[TD], /) -> StructSchema[TD, Never, Never]: ...
@overload
def Struct[TD: Mapping[str, object], RD, RE](
    typed_dict: type[TD], /, **fields: Codec[object, object, RD, RE]
) -> StructSchema[TD, RD, RE]: ...
def Struct(
    typed_dict: type[Mapping[str, object]], /, **fields: Codec[object, object, object, object]
) -> StructSchema[Any, Any, Any]:
    """A mapping with the keys of ``typed_dict`` (Effect's ``Struct``).
    Each key's schema comes from its annotation unless given here; a name
    the TypedDict lacks raises ``TypeError``, as does an annotation with no
    schema (see ``pyfect.schema`` for which annotations have one)."""
    given = {name: codec.__codec__() for name, codec in fields.items()}
    schemas = typed_dict_fields(typed_dict, given)
    node = typed_dict_ast(typed_dict, schemas if given else None)
    return StructSchema(node, schemas)

StructWithRest

StructWithRest[TD: Mapping[str, object], RD, RE](schema, *records) -> StructWithRestSchema[TD, RD, RE]

schema's keys, and any other key one of records takes, with its value (Effect's StructWithRest); the checks of all of them run. A TypedDict is open, so its type allows the other keys; declare their type with extra_items= (PEP 728, typing_extensions.TypedDict), which Struct reads as a string record by itself. A key both declare raises ValueError, as does a struct or record with an encoding of its own.

ParameterTypeDescription
schemaStructSchema[TD, RD, RE]
recordsRecordSchema[Any, Any, Any, Any, RD, RE] = ()

Returns StructWithRestSchema[TD, RD, RE]

def StructWithRest[TD: Mapping[str, object], RD, RE](
    schema: StructSchema[TD, RD, RE], /, *records: RecordSchema[Any, Any, Any, Any, RD, RE]
) -> StructWithRestSchema[TD, RD, RE]:
    """``schema``'s keys, and any other key one of ``records`` takes, with
    its value (Effect's ``StructWithRest``); the checks of all of them run.
    A TypedDict is open, so its type allows the other keys; declare their
    type with ``extra_items=`` (PEP 728, ``typing_extensions.TypedDict``),
    which ``Struct`` reads as a string record by itself. A key both declare
    raises ``ValueError``, as does a struct or record with an encoding of
    its own."""
    nodes = [schema.ast, *(r.ast for r in records)]
    objects = [node for node in nodes if isinstance(node, ast.Objects)]
    if len(objects) != len(nodes):
        raise ValueError("StructWithRest does not support encodings")
    node = ast.struct_with_rest(objects[0], objects[1:])
    return StructWithRestSchema(node, schema, records)

suspend

suspend[T, E, RD, RE](f) -> Bottom[T, E, RD, RE]

The schema f returns, made on first use: for a schema that refers to itself (Effect's suspend).

ParameterTypeDescription
fCallable[[], Codec[T, E, RD, RE]]

Returns Bottom[T, E, RD, RE]

def suspend[T, E, RD, RE](f: Callable[[], Codec[T, E, RD, RE]], /) -> Bottom[T, E, RD, RE]:
    """The schema ``f`` returns, made on first use: for a schema that
    refers to itself (Effect's ``suspend``)."""
    return Bottom(ast.Suspend(lambda: f().__codec__().ast))

encode_keys

encode_keys(mapping) -> EncodeKeys

The struct's keys renamed on the encoded side, {key: encoded key} (Effect's encodeKeys). Two keys encoding to one name, or a mapping key that is not a field, raise ValueError.

ParameterTypeDescription
mappingMapping[str, str]

Returns EncodeKeys

def encode_keys(mapping: Mapping[str, str], /) -> EncodeKeys:
    """The struct's keys renamed on the encoded side, ``{key: encoded
    key}`` (Effect's ``encodeKeys``). Two keys encoding to one name, or a
    mapping key that is not a field, raise ``ValueError``."""
    return EncodeKeys(mapping)

extend_to

extend_to[TD: Mapping[str, object], A: Mapping[str, object]](typed_dict, derive, **fields) -> ExtendTo[TD, A]

The struct decoded into typed_dict, a struct with its keys and more, each new key derive[key](value) when that is Some; the new keys are dropped when encoding (Effect's extendTo). A new key's schema comes from its annotation unless given in fields; derive must have exactly the new keys (else ValueError).

ParameterTypeDescription
typed_dicttype[TD]
deriveMapping[str, Callable[[A], Option[object]]]
fieldsCodec[object, object, Any, Any] = {}

Returns ExtendTo[TD, A]

def extend_to[TD: Mapping[str, object], A: Mapping[str, object]](
    typed_dict: type[TD],
    derive: Mapping[str, Callable[[A], Option[object]]],
    /,
    **fields: Codec[object, object, Any, Any],
) -> ExtendTo[TD, A]:
    """The struct decoded into ``typed_dict``, a struct with its keys and
    more, each new key ``derive[key](value)`` when that is ``Some``; the
    new keys are dropped when encoding (Effect's ``extendTo``). A new key's
    schema comes from its annotation unless given in ``fields``; ``derive``
    must have exactly the new keys (else ``ValueError``)."""
    return ExtendTo(typed_dict, derive, fields)

TaggedStruct

TaggedStruct[TD: Mapping[str, object]](typed_dict: type[TD], /) -> TaggedStructSchema[TD, Never, Never]
TaggedStruct[TD: Mapping[str, object], RD, RE](typed_dict: type[TD], /, **fields: Codec[object, object, RD, RE] = {}) -> TaggedStructSchema[TD, RD, RE]

Struct(typed_dict, **fields) of a TypedDict whose _tag key is one literal (_tag: Literal["A"]), a case of a tagged union (Effect's TaggedStruct); make fills the tag in (S.tag) unless fields give the _tag schema. Any other _tag raises TypeError.

ParameterTypeDescription
typed_dict
fields= {}
@overload
def TaggedStruct[TD: Mapping[str, object]](
    typed_dict: type[TD], /
) -> TaggedStructSchema[TD, Never, Never]: ...
@overload
def TaggedStruct[TD: Mapping[str, object], RD, RE](
    typed_dict: type[TD], /, **fields: Codec[object, object, RD, RE]
) -> TaggedStructSchema[TD, RD, RE]: ...
def TaggedStruct(
    typed_dict: type[Mapping[str, object]], /, **fields: Codec[object, object, object, object]
) -> TaggedStructSchema[Any, Any, Any]:
    """``Struct(typed_dict, **fields)`` of a TypedDict whose ``_tag`` key
    is one literal (``_tag: Literal["A"]``), a case of a tagged union
    (Effect's ``TaggedStruct``); ``make`` fills the tag in (``S.tag``)
    unless ``fields`` give the ``_tag`` schema. Any other ``_tag`` raises
    ``TypeError``."""
    hint = typed_dict_hints(typed_dict).get("_tag")
    literals = get_args(hint) if get_origin(hint) is TypingLiteral else ()
    if len(literals) != 1 or "_tag" in optional_keys(typed_dict):
        raise TypeError(f'{typed_dict_name(typed_dict)} needs a required "_tag" key of one literal')
    struct = Struct(typed_dict, **{"_tag": tag(literals[0]), **fields})
    return TaggedStructSchema(struct.ast, struct.fields, literals[0])

TaggedUnion

TaggedUnion[A = Never, I = Never, RD = Never, RE = Never](*cases) -> TaggedUnionSchema[A, I, RD, RE]

The union of cases told apart by "_tag" (Effect's TaggedUnion): each a TaggedClass, a TaggedStruct or any schema with a "_tag" literal.

ParameterTypeDescription
casesCodec[A, I, RD, RE] = ()

Returns TaggedUnionSchema[A, I, RD, RE]

def TaggedUnion[A = Never, I = Never, RD = Never, RE = Never](
    *cases: Codec[A, I, RD, RE],
) -> TaggedUnionSchema[A, I, RD, RE]:
    """The union of ``cases`` told apart by ``"_tag"`` (Effect's
    ``TaggedUnion``): each a ``TaggedClass``, a ``TaggedStruct`` or any
    schema with a ``"_tag"`` literal."""
    return to_tagged_union("_tag")(Union(*cases))

tag_default_omit

tag_default_omit[L: LiteralInput](literal) -> DecodeToSchema[L, L, Never, Never]

A "_tag" field holding literal, filled in when decoding a mapping without it and left out when encoding (Effect's tagDefaultOmit): S.Struct(A, _tag=S.tag_default_omit("A")); make fills it in too (S.tag).

ParameterTypeDescription
literalL

Returns DecodeToSchema[L, L, Never, Never]

def tag_default_omit[L: LiteralInput](literal: L, /) -> DecodeToSchema[L, L, Never, Never]:
    """A ``"_tag"`` field holding ``literal``, filled in when decoding a
    mapping without it and left out when encoding (Effect's
    ``tagDefaultOmit``): ``S.Struct(A, _tag=S.tag_default_omit("A"))``;
    ``make`` fills it in too (``S.tag``)."""
    return tag(literal).pipe(with_decoding_default_key(succeed(literal), encoding_strategy="omit"))

to_tagged_union

to_tagged_union(tag) -> ToTaggedUnion

The union with its cases kept by the literal each holds under tag, nested unions' cases included (Effect's toTaggedUnion). A case without a string or number literal there raises ValueError, as does a literal two cases share (1 and "1" are one).

ParameterTypeDescription
tagstr

Returns ToTaggedUnion

def to_tagged_union(tag: str, /) -> ToTaggedUnion:
    """The union with its cases kept by the literal each holds under
    ``tag``, nested unions' cases included (Effect's ``toTaggedUnion``).
    A case without a string or number literal there raises ``ValueError``,
    as does a literal two cases share (``1`` and ``"1"`` are one)."""
    return ToTaggedUnion(tag)

TemplateLiteral

TemplateLiteral(parts: list[TemplateLiteralPart] | tuple[TemplateLiteralPart, ...], /) -> TemplateLiteralSchema
TemplateLiteral(*parts: TemplateLiteralPart = ()) -> TemplateLiteralSchema

The strings made of parts, kept as they are (Effect's TemplateLiteral): Expected a string matching template literal parts otherwise. The parts are given as arguments or, as in Effect, as one list or tuple. A part with an encoding raises ValueError (use TemplateLiteralParser).

ParameterTypeDescription
parts= ()
@overload
def TemplateLiteral(
    parts: list[TemplateLiteralPart] | tuple[TemplateLiteralPart, ...], /
) -> TemplateLiteralSchema: ...
@overload
def TemplateLiteral(*parts: TemplateLiteralPart) -> TemplateLiteralSchema: ...
def TemplateLiteral(*parts: Any) -> TemplateLiteralSchema:
    """The strings made of ``parts``, kept as they are (Effect's
    ``TemplateLiteral``): ``Expected a string matching template literal
    parts`` otherwise. The parts are given as arguments or, as in Effect,
    as one list or tuple. A part with an encoding raises ``ValueError``
    (use ``TemplateLiteralParser``)."""
    parts = one_or_many(parts)
    return TemplateLiteralSchema(TemplateLiteralNode(_nodes(parts)), parts)

TemplateLiteralParser

TemplateLiteralParser[RD = Never, RE = Never](parts: list[Codec[Any, Any, RD, RE] | LiteralPart] | tuple[Codec[Any, Any, RD, RE] | LiteralPart, ...], /) -> TemplateLiteralParserSchema[RD, RE]
TemplateLiteralParser[RD = Never, RE = Never](*parts: Codec[Any, Any, RD, RE] | LiteralPart = ()) -> TemplateLiteralParserSchema[RD, RE]

The strings made of parts, decoded into a tuple of the parts' values (Effect's TemplateLiteralParser): a literal part gives its literal, a schema part its decoded value. A part may transform (its encoded side is the template's part). The split is greedy, so encoding a tuple and decoding the string may give another tuple when a segment holds a separator.

ParameterTypeDescription
parts= ()
@overload
def TemplateLiteralParser[RD = Never, RE = Never](
    parts: list[Codec[Any, Any, RD, RE] | LiteralPart]
    | tuple[Codec[Any, Any, RD, RE] | LiteralPart, ...],
    /,
) -> TemplateLiteralParserSchema[RD, RE]: ...
@overload
def TemplateLiteralParser[RD = Never, RE = Never](
    *parts: Codec[Any, Any, RD, RE] | LiteralPart,
) -> TemplateLiteralParserSchema[RD, RE]: ...
def TemplateLiteralParser(*parts: Any) -> TemplateLiteralParserSchema[Any, Any]:
    """The strings made of ``parts``, decoded into a tuple of the parts'
    values (Effect's ``TemplateLiteralParser``): a literal part gives its
    literal, a schema part its decoded value. A part may transform (its
    encoded side is the template's part). The split is greedy, so encoding
    a tuple and decoding the string may give another tuple when a segment
    holds a separator."""
    parts = one_or_many(parts)
    return TemplateLiteralParserSchema(template_literal_parser(_nodes(parts)), parts)

to_codec_array_from_single

to_codec_array_from_single[T_, E, RD, RE](schema) -> Bottom[T_, E, RD, RE]

schema with every array (in structs, unions and arrays) also decoding a single string as a one-element list; encoding is unchanged. A comma-separated string is not split.

ParameterTypeDescription
schemaCodec[T_, E, RD, RE]

Returns Bottom[T_, E, RD, RE]

def to_codec_array_from_single[T_, E, RD, RE](
    schema: Codec[T_, E, RD, RE], /
) -> Bottom[T_, E, RD, RE]:
    """``schema`` with every array (in structs, unions and arrays) also
    decoding a single string as a one-element list; encoding is
    unchanged. A comma-separated string is not split."""
    return Bottom(_Walk()(schema.__codec__().ast))

to_codec_go_json

to_codec_go_json[T, E, RD, RE](schema) -> Bottom[T, JsonValue, RD, RE]

schema reading JSON a Go program wrote. A declaration with no codec is read as JSON.

ParameterTypeDescription
schemaCodec[T, E, RD, RE]

Returns Bottom[T, JsonValue, RD, RE]

def to_codec_go_json[T, E, RD, RE](schema: Codec[T, E, RD, RE], /) -> Bottom[T, JsonValue, RD, RE]:
    """``schema`` reading JSON a Go program wrote. A declaration with no codec is read as JSON."""
    canonical = to_codec_json_asts([schema.__codec__().ast])[0]
    return Bottom(_on_last(_nil_as_empty)(_GoNil()(canonical)))

to_codec_json

to_codec_json[T, E, RD, RE](schema) -> Bottom[T, JsonValue, RD, RE]

schema decoding its values from JSON (Effect's toCodecJson).

ParameterTypeDescription
schemaCodec[T, E, RD, RE]

Returns Bottom[T, JsonValue, RD, RE]

def to_codec_json[T, E, RD, RE](schema: Codec[T, E, RD, RE], /) -> Bottom[T, JsonValue, RD, RE]:
    """``schema`` decoding its values from JSON (Effect's ``toCodecJson``)."""
    return Bottom(_Derivation()(schema.__codec__().ast))

to_codec_string_tree

to_codec_string_tree[T, E, RD, RE](schema) -> Bottom[T, StringTree, RD, RE]

schema decoding its values from a string tree (Effect's toCodecStringTree). A declaration with no codec annotation is a ValueError.

ParameterTypeDescription
schemaCodec[T, E, RD, RE]

Returns Bottom[T, StringTree, RD, RE]

def to_codec_string_tree[T, E, RD, RE](
    schema: Codec[T, E, RD, RE], /
) -> Bottom[T, StringTree, RD, RE]:
    """``schema`` decoding its values from a string tree (Effect's
    ``toCodecStringTree``). A declaration with no codec annotation is a
    ``ValueError``."""
    return Bottom(to_codec_string_tree_ast(schema.__codec__().ast))

to_differ_json_patch

to_differ_json_patch[T, E](schema) -> Differ[T, JsonPatch]

A patch that changes nothing returns the old value itself. Patching decodes through schema's JSON form, so a value it refuses raises SchemaError.

ParameterTypeDescription
schemaCodec[T, E, object, object]

Returns Differ[T, JsonPatch]

def to_differ_json_patch[T, E](schema: Codec[T, E, object, object], /) -> Differ[T, JsonPatch]:
    """A patch that changes nothing returns the old value itself. Patching decodes through
    ``schema``'s JSON form, so a value it refuses raises ``SchemaError``."""
    serializer: Any = to_codec_json(schema)
    get = encode_sync(serializer)
    set_ = decode_sync(serializer)

    def patch(old_value: T, patch: JsonPatch) -> T:
        value = get(old_value)
        patched = json_patch.apply(patch, value)
        return old_value if patched is value else set_(patched)

    return Differ(
        empty=[],
        diff=lambda old_value, new_value: json_patch.get(get(old_value), get(new_value)),
        combine=lambda first, second: [*first, *second],
        patch=patch,
    )

to_encoder_xml

to_encoder_xml[T, E, RD, RE](codec, /, *, root_name=None, array_item_name='item', pretty=True, indent='  ', sort_keys=True) -> Callable[[T], Effect[str, SchemaError, RE]]

A function from a value to its XML text. The root is root_name, else the schema's identifier or title, else root. A declaration with no codec is a ValueError.

ParameterTypeDescription
codecCodec[T, E, RD, RE]
root_namestr | None = None
array_item_namestr = 'item'
prettybool = True
indentstr = ' '
sort_keysbool = True

Returns Callable[[T], Effect[str, SchemaError, RE]]

def to_encoder_xml[T, E, RD, RE](
    codec: Codec[T, E, RD, RE],
    /,
    *,
    root_name: str | None = None,
    array_item_name: str = "item",
    pretty: bool = True,
    indent: str = "  ",
    sort_keys: bool = True,
) -> Callable[[T], Effect[str, SchemaError, RE]]:
    """A function from a value to its XML text. The root is ``root_name``, else the schema's
    identifier or title, else ``root``. A declaration with no codec is a ``ValueError``."""
    resolved = codec.__codec__().ast.resolve() or {}
    name = root_name or resolved.get("identifier") or resolved.get("title") or "root"
    options = _Options(array_item_name, pretty, indent, sort_keys)
    serialize: Callable[[T], Effect[Any, SchemaError, RE]] = encode_effect(
        to_codec_string_tree(codec)
    )
    return lambda value: serialize(value).map(lambda tree: _to_xml(str(name), tree, options))

to_equivalence

to_equivalence[T](schema) -> Equivalence[T]

When two values of schema's decoded side are the same (Effect's toEquivalence).

ParameterTypeDescription
schemaCodec[T, object, object, object]

Returns Equivalence[T]

def to_equivalence[T](schema: Codec[T, object, object, object], /) -> Equivalence[T]:
    """When two values of ``schema``'s decoded side are the same (Effect's
    ``toEquivalence``)."""
    return _Derivation()(schema.__codec__().ast)

to_formatter

to_formatter[T](schema, /, *, on_before=None) -> Formatter[T]

schema's decoded values as text (Effect's toFormatter).

ParameterTypeDescription
schemaCodec[T, object, object, object]
on_beforeOnBefore | None = None

Returns Formatter[T]

def to_formatter[T](
    schema: Codec[T, object, object, object], /, *, on_before: OnBefore | None = None
) -> Formatter[T]:
    """``schema``'s decoded values as text (Effect's ``toFormatter``)."""
    return _Derivation(on_before)(schema.__codec__().ast)

override_to_codec_iso

override_to_codec_iso[T, I](to, transformation) -> Callable[[Codec[T, Any, Any, Any]], Bottom[T, Any, Any, Any]]

schema whose plain form is to, read through transformation.

ParameterTypeDescription
toCodec[I, object, object, object]
transformationTransformation[T, I]

Returns Callable[[Codec[T, Any, Any, Any]], Bottom[T, Any, Any, Any]]

def override_to_codec_iso[T, I](
    to: Codec[I, object, object, object], transformation: Transformation[T, I], /
) -> Callable[[Codec[T, Any, Any, Any]], Bottom[T, Any, Any, Any]]:
    """``schema`` whose plain form is ``to``, read through ``transformation``."""
    link = ast.Link(to.__codec__().ast, transformation)

    def get_link(_: tuple[ast.AST, ...]) -> ast.Link:
        return link

    def override(schema: Codec[T, Any, Any, Any]) -> Bottom[T, Any, Any, Any]:
        return Bottom(ast.annotate(schema.__codec__().ast, {"to_codec_iso": get_link}))

    return override

to_codec_iso

to_codec_iso[T](schema) -> Bottom[T, Any]
ParameterTypeDescription
schemaCodec[T, object, object, object]

Returns Bottom[T, Any]

def to_codec_iso[T](schema: Codec[T, object, object, object], /) -> Bottom[T, Any]:
    return Bottom(_Derivation()(schema.__codec__().ast.to_type()))

to_iso

to_iso[T](schema) -> optic.Iso[T, Any]
ParameterTypeDescription
schemaCodec[T, object, object, object]

Returns optic.Iso[T, Any]

def to_iso[T](schema: Codec[T, object, object, object], /) -> optic.Iso[T, Any]:
    serializer: Any = to_codec_iso(schema)
    return optic.make_iso(encode_sync(serializer), decode_sync(serializer))

to_iso_focus

to_iso_focus(_) -> optic.Iso[Any, Any]
ParameterTypeDescription
_Codec[object, object, object, object]

Returns optic.Iso[Any, Any]

def to_iso_focus(_: Codec[object, object, object, object], /) -> optic.Iso[Any, Any]:
    return optic.Id()

to_iso_source

to_iso_source[T](_) -> optic.Iso[T, T]
ParameterTypeDescription
_Codec[T, object, object, object]

Returns optic.Iso[T, T]

def to_iso_source[T](_: Codec[T, object, object, object], /) -> optic.Iso[T, T]:
    return optic.Id()

to_strategy

to_strategy[T](schema) -> SearchStrategy[T]

Values of schema's decoded side that pass its checks and that schema encodes (a JSON string holds no NaN, say).

Common checks (bounds, lengths, sizes, patterns, integers) shape what is drawn; every check also filters it. A declaration is drawn with its to_arbitrary annotation (its type parameters' strategies in, a strategy out), else through its to_codec_arbitrary, to_codec_json or to_codec link. Raises ValueError when the schema has no finite value or a declaration says neither.

ParameterTypeDescription
schemaCodec[T, object, object, object]

Returns SearchStrategy[T]

def to_strategy[T](schema: Codec[T, object, object, object], /) -> SearchStrategy[T]:
    """Values of ``schema``'s decoded side that pass its checks and that
    ``schema`` encodes (a JSON string holds no ``NaN``, say).

    Common checks (bounds, lengths, sizes, patterns, integers) shape what is
    drawn; every check also filters it. A declaration is drawn with its
    ``to_arbitrary`` annotation (its type parameters' strategies in, a
    strategy out), else through its ``to_codec_arbitrary``, ``to_codec_json``
    or ``to_codec`` link. Raises ``ValueError`` when the schema has no
    finite value or a declaration says neither."""
    from pyfect.schema._strategy import derive

    return derive(schema.__codec__().ast)

decode

decode[T, RD = Never, RE = Never](transformation) -> Decode[T, RD, RE]

The schema, then transformation on its decoded values (Effect's decode).

ParameterTypeDescription
transformationTransformation[T, T, RD, RE]

Returns Decode[T, RD, RE]

def decode[T, RD = Never, RE = Never](
    transformation: Transformation[T, T, RD, RE], /
) -> Decode[T, RD, RE]:
    """The schema, then ``transformation`` on its decoded values (Effect's
    ``decode``)."""
    return Decode(transformation)

decode_to

decode_to[T, M, RD, RE](to: Codec[T, M, RD, RE], /) -> DecodeTo[T, M, RD, RE]
decode_to[T, M, F, RD, RE](to: Codec[T, M, RD, RE], transformation: Transformation[M, F, RD, RE], /) -> DecodeTo[T, F, RD, RE]

The source's values decoded through transformation (none: kept as they are) into to's (Effect's decodeTo).

ParameterTypeDescription
to
transformation= None
@overload
def decode_to[T, M, RD, RE](to: Codec[T, M, RD, RE], /) -> DecodeTo[T, M, RD, RE]: ...
@overload
def decode_to[T, M, F, RD, RE](
    to: Codec[T, M, RD, RE], transformation: Transformation[M, F, RD, RE], /
) -> DecodeTo[T, F, RD, RE]: ...
def decode_to(
    to: Codec[Any, Any, Any, Any],
    transformation: Transformation[Any, Any, Any, Any] | None = None,
    /,
) -> DecodeTo[Any, Any, Any, Any]:
    """The source's values decoded through ``transformation`` (none: kept
    as they are) into ``to``'s (Effect's ``decodeTo``)."""
    return DecodeTo(to, passthrough() if transformation is None else transformation)

encode

encode[E, RD = Never, RE = Never](transformation) -> Encode[E, RD, RE]

transformation on the encoded values, before the schema (Effect's encode).

ParameterTypeDescription
transformationTransformation[E, E, RD, RE]

Returns Encode[E, RD, RE]

def encode[E, RD = Never, RE = Never](
    transformation: Transformation[E, E, RD, RE], /
) -> Encode[E, RD, RE]:
    """``transformation`` on the encoded values, before the schema (Effect's
    ``encode``)."""
    return Encode(transformation)

encode_to

encode_to[M, E, RD, RE](to: Source[M, E, RD, RE], /) -> EncodeTo[M, E, RD, RE]
encode_to[M, F, E, RD, RE](to: Source[M, E, RD, RE], transformation: Transformation[F, M, RD, RE], /) -> EncodeTo[F, E, RD, RE]

The schema's Encoded encoded further into to's: s.pipe( S.encode_to(to, t)) is to.pipe(S.decode_to(s, t)) (Effect's encodeTo).

ParameterTypeDescription
to
transformation= None
@overload
def encode_to[M, E, RD, RE](to: Source[M, E, RD, RE], /) -> EncodeTo[M, E, RD, RE]: ...
@overload
def encode_to[M, F, E, RD, RE](
    to: Source[M, E, RD, RE], transformation: Transformation[F, M, RD, RE], /
) -> EncodeTo[F, E, RD, RE]: ...
def encode_to(
    to: Source[Any, Any, Any, Any],
    transformation: Transformation[Any, Any, Any, Any] | None = None,
    /,
) -> EncodeTo[Any, Any, Any, Any]:
    """The schema's Encoded encoded further into ``to``'s: ``s.pipe(
    S.encode_to(to, t))`` is ``to.pipe(S.decode_to(s, t))`` (Effect's
    ``encodeTo``)."""
    return EncodeTo(to, passthrough() if transformation is None else transformation)

flip

flip[T, E, RD, RE](schema: FlipSchema[T, E, RD, RE], /) -> Codec[E, T, RE, RD]
flip[T, E, RD, RE](schema: Codec[T, E, RD, RE], /) -> FlipSchema[E, T, RE, RD]

The schema decoding its Type into its Encoded (Effect's flip); the flip of a flip is the original schema, rebuilt on the flipped node (so checks added in between stay).

ParameterTypeDescription
schema
@overload
def flip[T, E, RD, RE](  # pyright: ignore[reportOverlappingOverload]
    schema: FlipSchema[T, E, RD, RE], /
) -> Codec[E, T, RE, RD]: ...
@overload
def flip[T, E, RD, RE](schema: Codec[T, E, RD, RE], /) -> FlipSchema[E, T, RE, RD]: ...
def flip(schema: Codec[Any, Any, Any, Any], /) -> Codec[Any, Any, Any, Any]:
    """The schema decoding its Type into its Encoded (Effect's ``flip``);
    the flip of a flip is the original schema, rebuilt on the flipped node
    (so checks added in between stay)."""
    if isinstance(schema, FlipSchema):
        node = schema.ast.flip()
        original = schema.schema.__codec__()
        return original if original.ast is node else replace(original, ast=node)
    return FlipSchema(schema.__codec__().ast.flip(), schema)
link[T, M](encode_to, transformation) -> ast.Link

A declaration's codec step (Effect's link<T>()(encodeTo, t)): its T values encoded through transformation to encode_to, for a to_codec / to_codec_json annotation.

ParameterTypeDescription
encode_toCodec[M, object, object, object]
transformationTransformation[T, M]

Returns ast.Link

def link[T, M](
    encode_to: Codec[M, object, object, object], transformation: Transformation[T, M], /
) -> ast.Link:
    """A declaration's codec step (Effect's ``link<T>()(encodeTo, t)``): its
    ``T`` values encoded through ``transformation`` to ``encode_to``, for a
    ``to_codec`` / ``to_codec_json`` annotation."""
    return ast.Link(encode_to.__codec__().ast, transformation)

to_encoded

to_encoded[E](schema) -> Bottom[E]

The schema's encoded side (Effect's toEncoded).

ParameterTypeDescription
schemaCodec[object, E, object, object]

Returns Bottom[E]

def to_encoded[E](schema: Codec[object, E, object, object], /) -> Bottom[E]:
    """The schema's encoded side (Effect's ``toEncoded``)."""
    return Bottom(ast.to_encoded(schema.__codec__().ast))

to_type

to_type[T](schema) -> Bottom[T]

The schema's decoded side: it checks a Type value and keeps it (Effect's toType).

ParameterTypeDescription
schemaCodec[T, object, object, object]

Returns Bottom[T]

def to_type[T](schema: Codec[T, object, object, object], /) -> Bottom[T]:
    """The schema's decoded side: it checks a Type value and keeps it
    (Effect's ``toType``)."""
    return Bottom(schema.__codec__().ast.to_type())

Tree

Tree[T, E, RD, RE](node) -> Bottom[TreeValue[T], TreeValue[E], RD, RE]

The recursive schema of trees of node's values.

ParameterTypeDescription
nodeCodec[T, E, RD, RE]

Returns Bottom[TreeValue[T], TreeValue[E], RD, RE]

def Tree[T, E, RD, RE](node: Codec[T, E, RD, RE], /) -> Bottom[TreeValue[T], TreeValue[E], RD, RE]:
    """The recursive schema of trees of ``node``'s values."""
    tree: Bottom[TreeValue[T], TreeValue[E], RD, RE] = suspend(lambda: schema)
    schema = Union(node, Array(tree), Record(String, tree))
    return schema

Modules