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#
| Attribute | Type | Description |
|---|---|---|
BooleanLiterals | DecodeToSchema[bool, str] | A |
FalseLiterals | LiteralsSchema[FalseLiteral] | |
TrueLiterals | LiteralsSchema[TrueLiteral] | |
is_between | Between[float] | |
is_between_big_int | Between[int] | |
is_between_date | Between[datetime] | |
is_greater_than | Bound[float] | |
is_greater_than_big_int | Bound[int] | |
is_greater_than_date | Bound[datetime] | |
is_greater_than_or_equal_to | Bound[float] | |
is_greater_than_or_equal_to_big_int | Bound[int] | |
is_greater_than_or_equal_to_date | Bound[datetime] | |
is_less_than | Bound[float] | |
is_less_than_big_int | Bound[int] | |
is_less_than_date | Bound[datetime] | |
is_less_than_or_equal_to | Bound[float] | |
is_less_than_or_equal_to_big_int | Bound[int] | |
is_less_than_or_equal_to_date | Bound[datetime] | |
URL | Bottom[Url] | A parsed URL, a |
BigIntFromString | DecodeToSchema[int, str] | |
BooleanFromBit | DecodeToSchema[bool, int] |
|
Bytes | Bottom[bytes] |
|
BytesFromBase64 | DecodeToSchema[bytes, str] | Bytes from Base64 text (Effect's |
BytesFromBase64Url | DecodeToSchema[bytes, str] | |
BytesFromHex | DecodeToSchema[bytes, str] | |
ByteSizeFromBigInt | DecodeToSchema[_ByteSize, int] | |
ByteSizeFromNumber | DecodeToSchema[_ByteSize, float] | |
ByteSizeFromString | DecodeToSchema[_ByteSize, str] | |
DateTimeUtcFromDate | DecodeToSchema[datetime, datetime] | A UTC |
DateTimeUtcFromMillis | DecodeToSchema[datetime, int] | A UTC |
DateTimeUtcFromString | DecodeToSchema[datetime, str] | A UTC |
DateTimeZonedFromString | DecodeToSchema[datetime, str] | |
FiniteFromString | DecodeToSchema[float, str] | |
NumberFromString | DecodeToSchema[float, str] | A number from its text, as JavaScript's |
StringFromBase64 | DecodeToSchema[str, str] | |
StringFromBase64Url | DecodeToSchema[str, str] | |
StringFromHex | DecodeToSchema[str, str] | |
StringFromUriComponent | DecodeToSchema[str, str] | |
TimeZoneFromString | DecodeToSchema[tzinfo, str] | |
TimeZoneNamedFromString | DecodeToSchema[ZoneInfo, str] | |
Trim | DecodeToSchema[str, str] | A string, trimmed when decoding. |
UnknownFromJsonString | DecodeToSchema[object, str] | Any JSON value, from its text. |
URLFromString | DecodeToSchema[Url, str] | |
BigDecimal | Bottom[bd.BigDecimal] | A |
BigDecimalFromString | DecodeToSchema[bd.BigDecimal, str] | A |
RegExp | Bottom[re.Pattern[str]] | A compiled |
is_between_big_decimal | Between[bd.BigDecimal] | |
is_greater_than_big_decimal | Bound[bd.BigDecimal] | |
is_greater_than_or_equal_to_big_decimal | Bound[bd.BigDecimal] | |
is_less_than_big_decimal | Bound[bd.BigDecimal] | |
is_less_than_or_equal_to_big_decimal | Bound[bd.BigDecimal] | |
DurationFromIsoString | DecodeToSchema[_duration.Duration, str] | A |
DurationFromMillis | DecodeToSchema[_duration.Duration, float] | A |
DurationFromNanos | DecodeToSchema[_duration.Duration, int] | A |
DurationFromString | DecodeToSchema[_duration.Duration, str] | A |
DnsAaaaRecord | Bottom[Aaaa, Aaaa, Never, Never] | |
DnsARecord | Bottom[A, A, Never, Never] | |
DnsCaaRecord | Bottom[Caa, Caa, Never, Never] | |
DnsCnameRecord | Bottom[Cname, Cname, Never, Never] | |
DnsMxRecord | Bottom[Mx, Mx, Never, Never] | |
DnsNaptrRecord | Bottom[Naptr, Naptr, Never, Never] | |
DnsNsRecord | Bottom[Ns, Ns, Never, Never] | |
DnsPtrRecord | Bottom[Ptr, Ptr, Never, Never] | |
DnsRecord | Bottom[dns.DnsRecord] | Any DNS record ( |
DnsRecordType | LiteralsSchema[dns.RecordType] | A DNS record type ( |
DnsSoaRecord | Bottom[Soa, Soa, Never, Never] | |
DnsSrvRecord | Bottom[Srv, Srv, Never, Never] | |
DnsTlsaRecord | Bottom[Tlsa, Tlsa, Never, Never] | |
DnsTxtRecord | Bottom[Txt, Txt, Never, Never] | |
DomainName | Bottom[DomainName, str, Never, Never] | A normalized |
DomainNameFromString | DecodeToSchema[DomainName, str, Never, Never] | |
Host | Bottom[host.Host, Any] | An IP address, a scoped IPv6 literal or a domain name. |
HostFromString | Bottom[host.Host, str] | |
HostPort | Bottom[host.HostPort] | |
HostPortFromString | DecodeToSchema[HostPort, str, Never, Never] | |
InetAddress | Bottom[na.InetAddress] | |
InetAddressFromString | DecodeToSchema[InetAddressV4 | InetAddressV6, str, Never, Never] | |
InetAddressV4 | Bottom[na.InetAddressV4] | |
InetAddressV6 | Bottom[na.InetAddressV6] | |
IpAddress | Bottom[na.IpAddress] | An IPv4 or IPv6 address. |
IpAddressFromString | DecodeToSchema[IPv4Address | IPv6Address, str, Never, Never] | |
IpInterface | Bottom[ip_interface.IpInterface] | |
IpInterfaceFromString | DecodeToSchema[IPv4Interface | IPv6Interface, str, Never, Never] | |
IpLinkLocalAddress | Bottom[IPv4Address | IPv6Address, IPv4Address | IPv6Address, Never, Never] | |
IpLinkLocalAddressFromString | Bottom[IPv4Address | IPv6Address, str, Never, Never] | |
IpLoopbackAddress | Bottom[IPv4Address | IPv6Address, IPv4Address | IPv6Address, Never, Never] | |
IpLoopbackAddressFromString | Bottom[IPv4Address | IPv6Address, str, Never, Never] | |
IpMulticastAddress | Bottom[IPv4Address | IPv6Address, IPv4Address | IPv6Address, Never, Never] | |
IpMulticastAddressFromString | Bottom[IPv4Address | IPv6Address, str, Never, Never] | |
IpNetwork | Bottom[ip_network.IpNetwork] | |
IpNetworkFromString | DecodeToSchema[IPv4Network | IPv6Network, str, Never, Never] | |
IpUnicastAddress | Bottom[IPv4Address | IPv6Address, IPv4Address | IPv6Address, Never, Never] | |
IpUnicastAddressFromString | Bottom[IPv4Address | IPv6Address, str, Never, Never] | |
IpUnspecifiedAddress | Bottom[IPv4Address | IPv6Address, IPv4Address | IPv6Address, Never, Never] | |
IpUnspecifiedAddressFromString | Bottom[IPv4Address | IPv6Address, str, Never, Never] | |
Ipv4Address | Bottom[IPv4Address] | An |
Ipv4AddressFromString | DecodeToSchema[IPv4Address, str, Never, Never] | |
Ipv4BroadcastAddress | Bottom[IPv4Address, IPv4Address, Never, Never] | |
Ipv4BroadcastAddressFromString | Bottom[IPv4Address, str, Never, Never] | |
Ipv4Interface | Bottom[IPv4Interface] | |
Ipv4InterfaceFromString | DecodeToSchema[IPv4Interface, str, Never, Never] | |
Ipv4Network | Bottom[IPv4Network] | |
Ipv4NetworkFromString | DecodeToSchema[IPv4Network, str, Never, Never] | |
Ipv4PrivateAddress | Bottom[IPv4Address, IPv4Address, Never, Never] | |
Ipv4PrivateAddressFromString | Bottom[IPv4Address, str, Never, Never] | |
Ipv6Address | Bottom[IPv6Address] | An |
Ipv6AddressFromString | DecodeToSchema[IPv6Address, str, Never, Never] | |
Ipv6Interface | Bottom[IPv6Interface] | |
Ipv6InterfaceFromString | DecodeToSchema[IPv6Interface, str, Never, Never] | |
Ipv6Network | Bottom[IPv6Network] | |
Ipv6NetworkFromString | DecodeToSchema[IPv6Network, str, Never, Never] | |
Ipv6UniqueLocalAddress | Bottom[IPv6Address, IPv6Address, Never, Never] | |
Ipv6UniqueLocalAddressFromString | Bottom[IPv6Address, str, Never, Never] | |
MacAddress | Bottom[na.MacAddress] | A |
MacAddressFromString | DecodeToSchema[MacAddress, str, Never, Never] | |
MacBroadcastAddress | Bottom[MacAddress, MacAddress, Never, Never] | |
MacBroadcastAddressFromString | Bottom[MacAddress, str, Never, Never] | |
MacLocallyAdministeredAddress | Bottom[MacAddress, MacAddress, Never, Never] | |
MacLocallyAdministeredAddressFromString | Bottom[MacAddress, str, Never, Never] | |
MacMulticastAddress | Bottom[MacAddress, MacAddress, Never, Never] | |
MacMulticastAddressFromString | Bottom[MacAddress, str, Never, Never] | |
MacUnicastAddress | Bottom[MacAddress, MacAddress, Never, Never] | |
MacUnicastAddressFromString | Bottom[MacAddress, str, Never, Never] | |
MacUniversallyAdministeredAddress | Bottom[MacAddress, MacAddress, Never, Never] | |
MacUniversallyAdministeredAddressFromString | Bottom[MacAddress, str, Never, Never] | |
ScopedIpv6Literal | Bottom[ScopedIpv6Literal, str, Never, Never] | A canonical |
ScopedIpv6LiteralFromString | DecodeToSchema[ScopedIpv6Literal, str, Never, Never] | |
SocketAddress | Bottom[na.SocketAddress] | |
UnixPathAddress | Bottom[na.UnixPathAddress] | |
UnixPathAddressFromString | DecodeToSchema[na.UnixPathAddress, str] | |
Any | Bottom[_Any] | Accepts anything, typed |
BigInt | Bottom[int] | An |
Boolean | Bottom[bool] | |
Char | Bottom[str] | A string of one character. |
Finite | Bottom[float] | A number that is not |
Int | Bottom[int] | An |
Natural | Bottom[int] | An |
Never | Bottom[_Never] | Accepts nothing. |
NonEmptyString | Bottom[str] | |
Null | Bottom[None] |
|
Number | Bottom[float] | An |
Port | Bottom[int] | An |
String | Bottom[str] | |
Trimmed | Bottom[str] | A string with no leading or trailing whitespace. |
Unknown | Bottom[object] | Accepts anything, typed |
SemVer | Bottom[semver.SemVer] | A |
SemVerFromString | DecodeToSchema[semver.SemVer, str] | |
SemVerRange | Bottom[semver_range.SemVerRange] | A |
SemVerRangeFromString | DecodeToSchema[semver_range.SemVerRange, str] | |
StandardSchemaV1FailureResult | Bottom[FailureResult, FailureResult, Never, Never] | The schema of a Standard Schema failure result: |
ByteSize | Bottom[_ByteSize] | A |
DateTimeUtc | Bottom[datetime] | An aware |
DateTimeZoned | Bottom[datetime] | An aware |
Duration | Bottom[DurationValue] | A |
Json | Bottom[JsonValue] | Any JSON value ( |
JsonObject | RecordSchema[str, JsonValue, str, JsonValue, Never, Never] | A string-keyed mapping of JSON values (Effect's |
TimeZone | Bottom[tzinfo] | A |
TimeZoneNamed | Bottom[ZoneInfo] | A |
TimeZoneOffset | Bottom[timezone] | A fixed-offset |
ObjectKeyword | Bottom[object] | Anything but a primitive; JSON holds an array or an object of JSON, a string tree those of string trees, as Effect's. |
Undefined | Bottom[None] | |
Void | Bottom[None, object] | Takes anything and gives |
Types#
| Type | Definition | Description |
|---|---|---|
TupleElement | type 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 |
Parse | type 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 |
DefectSchema | type DefectSchema = DecodeToSchema[object, JsonValue, Never, Never] | |
CheckOutput | type CheckOutput = JsonSchema | tuple[JsonSchema, Literal[True]] | |
OnExcessProperty | type OnExcessProperty = Literal['ignore', 'error'] | |
ReferencePolicy | type ReferencePolicy = Callable[[ReferenceCandidate], str | None] | The definition key of a candidate, or |
ToJsonSchema | type ToJsonSchema = Callable[[CheckContext], CheckOutput] | |
LiteralValue | type LiteralValue = LiteralString | int | float | bool | None | What a literal may be: a string, a number, a boolean or |
EncodingStrategy | type EncodingStrategy = Literal['passthrough', 'omit'] | What a defaulted key encodes to: its value, or nothing. |
Decoder | type Decoder[A, R = Never] = Codec[A, object, R, object] | |
Encoder | type Encoder[I, R = Never] = Codec[object, I, object, R] | |
Schema | type Schema[A] = Codec[A, object, object, object] | |
Top | type Top = Codec[object, object, object, object] | |
StringTree | type StringTree = str | Sequence[StringTree] | Mapping[str, StringTree] | None | Text leaves ( |
Equivalence | type Equivalence[A] = Callable[[A, A], bool] | Whether two values are the same (Effect's |
Formatter | type Formatter[A] = Callable[[A], str] | A value as text (Effect's |
OnBefore | type OnBefore = Callable[[ast.AST, Callable[[ast.AST], Formatter[Any]]], Formatter[Any] | None] | Takes a node before the derivation does: its formatter, or |
Source | type Source[T, E, RD, RE] = Codec[T, E, RD, RE] | OptionalKey[T, E, RD, RE] | What |
TreeValue | type 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). |
JsonValue | type JsonValue = bool | int | float | str | Sequence[JsonValue] | Mapping[str, JsonValue] | None | A JSON value (Effect's |
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).
| Parameter | Type | Description |
|---|---|---|
value | Codec[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(...))).
| Parameter | Type | Description |
|---|---|---|
value | Codec[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].
| Parameter | Type | Description |
|---|---|---|
value | Codec[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.
| Parameter | Type | Description |
|---|---|---|
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).
| Parameter | Type | Description |
|---|---|---|
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).
| Parameter | Type | Description |
|---|---|---|
value | Codec[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).
| Parameter | Type | Description |
|---|---|---|
schema | Codec[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.
| Parameter | Type | Description |
|---|---|---|
annotations | object = {} |
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.
| Parameter | Type | Description |
|---|---|---|
annotations | object = {} |
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.
| Parameter | Type | Description |
|---|---|---|
annotations | object = {} |
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.
| Parameter | Type | Description |
|---|---|---|
divisor | float | |
annotations | object = {} |
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.
| Parameter | Type | Description |
|---|---|---|
annotations | object = {} |
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).
| Parameter | Type | Description |
|---|---|---|
formatter | Callable[[T], str] = format_unknown | |
annotate | AnnotateBetween[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 makemake_is_greater_than#
make_is_greater_than[T: SupportsOrder](*, formatter=format_unknown, annotate=None) -> Bound[T]| Parameter | Type | Description |
|---|---|---|
formatter | Callable[[T], str] = format_unknown | |
annotate | Annotate[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]| Parameter | Type | Description |
|---|---|---|
formatter | Callable[[T], str] = format_unknown | |
annotate | Annotate[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]| Parameter | Type | Description |
|---|---|---|
formatter | Callable[[T], str] = format_unknown | |
annotate | Annotate[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]| Parameter | Type | Description |
|---|---|---|
formatter | Callable[[T], str] = format_unknown | |
annotate | Annotate[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).
| Parameter | Type | Description |
|---|---|---|
is_multiple | Callable[[T, T], bool] | |
formatter | Callable[[T], str] = format_unknown | |
annotate | Annotate[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 makeis_between_code_points#
is_between_code_points(minimum, maximum, **annotations) -> Filter[str]| Parameter | Type | Description |
|---|---|---|
minimum | float | |
maximum | float | |
annotations | object = {} |
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]| Parameter | Type | Description |
|---|---|---|
minimum | float | |
maximum | float | |
annotations | object = {} |
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]| Parameter | Type | Description |
|---|---|---|
minimum | float | |
maximum | float | |
annotations | object = {} |
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]| Parameter | Type | Description |
|---|---|---|
minimum | float | |
maximum | float | |
annotations | object = {} |
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]| Parameter | Type | Description |
|---|---|---|
max_code_points | float | |
annotations | object = {} |
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]| Parameter | Type | Description |
|---|---|---|
max_length | float | |
annotations | object = {} |
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]| Parameter | Type | Description |
|---|---|---|
max_properties | float | |
annotations | object = {} |
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]| Parameter | Type | Description |
|---|---|---|
max_size | float | |
annotations | object = {} |
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]| Parameter | Type | Description |
|---|---|---|
min_code_points | float | |
annotations | object = {} |
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]| Parameter | Type | Description |
|---|---|---|
min_length | float | |
annotations | object = {} |
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]| Parameter | Type | Description |
|---|---|---|
min_properties | float | |
annotations | object = {} |
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]| Parameter | Type | Description |
|---|---|---|
min_size | float | |
annotations | object = {} |
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).
| Parameter | Type | Description |
|---|---|---|
annotations | object = {} |
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.
| Parameter | Type | Description |
|---|---|---|
key_schema | Top | |
annotations | object = {} |
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).
| Parameter | Type | Description |
|---|---|---|
annotations | object = {} |
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.
| Parameter | Type | Description |
|---|---|---|
annotations | object = {} |
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.
| Parameter | Type | Description |
|---|---|---|
annotations | object = {} |
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]| Parameter | Type | Description |
|---|---|---|
annotations | object = {} |
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]| Parameter | Type | Description |
|---|---|---|
annotations | object = {} |
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.
| Parameter | Type | Description |
|---|---|---|
annotations | object = {} |
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]| Parameter | Type | Description |
|---|---|---|
suffix | str | |
annotations | object = {} |
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]| Parameter | Type | Description |
|---|---|---|
annotations | object = {} |
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]| Parameter | Type | Description |
|---|---|---|
part | str | |
annotations | object = {} |
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]| Parameter | Type | Description |
|---|---|---|
annotations | object = {} |
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).
| Parameter | Type | Description |
|---|---|---|
pattern | re.Pattern[str] | str | |
annotations | object = {} |
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]| Parameter | Type | Description |
|---|---|---|
prefix | str | |
annotations | object = {} |
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 +).
| Parameter | Type | Description |
|---|---|---|
annotations | object = {} |
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").
| Parameter | Type | Description |
|---|---|---|
annotations | object = {} |
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).
| Parameter | Type | Description |
|---|---|---|
annotations | object = {} |
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.
| Parameter | Type | Description |
|---|---|---|
annotations | object = {} |
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.
| Parameter | Type | Description |
|---|---|---|
annotations | object = {} |
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]| Parameter | Type | Description |
|---|---|---|
annotations | object = {} |
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.
| Parameter | Type | Description |
|---|---|---|
version | UUIDVersion | None = None | |
annotations | object = {} |
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.
| Parameter | Type | Description |
|---|---|---|
abort | bool = False | |
annotations | object = {} |
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 markfield#
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) -> AnyA 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.
| Parameter | Type | Description |
|---|---|---|
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.
| Parameter | Type | Description |
|---|---|---|
cls | Callable[P, T] | |
options | Unpack[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 constructArrayEnsure#
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.
| Parameter | Type | Description |
|---|---|---|
schema | Codec[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).
| Parameter | Type | Description |
|---|---|---|
schema | Codec[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).
| Parameter | Type | Description |
|---|---|---|
schema | Codec[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).
| Parameter | Type | Description |
|---|---|---|
schema | Codec[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).
| Parameter | Type | Description |
|---|---|---|
schema | Codec[A, I, RD, RE] | |
on_none_encoding | Literal['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).
| Parameter | Type | Description |
|---|---|---|
value | Codec[A, I, RD, RE] | |
label | str | None = None | |
disallow_encode | bool = 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.
| Parameter | Type | Description |
|---|---|---|
schema | Codec[A, I, RD, RE] | |
reviver | G.JsonReviver | None = None | |
replacer | G.JsonReplacer | None = None | |
space | int | 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.
| Parameter | Type | Description |
|---|---|---|
value | Codec[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.
| Parameter | Type | Description |
|---|---|---|
key | Codec[K, KI, RD, RE] | |
value | Codec[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")).
| Parameter | Type | Description |
|---|---|---|
literal | L |
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.
| Parameter | Type | Description |
|---|---|---|
default | Effect[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.
| Parameter | Type | Description |
|---|---|---|
error | Codec[E, EI, RD, RE] | |
defect | DefectCodec[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.
| Parameter | Type | Description |
|---|---|---|
error | Codec[E, EI, RD, RE] | |
defect | DefectCodec[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"]).
| Parameter | Type | Description |
|---|---|---|
value | Codec[A, AI, RD, RE] | |
error | Codec[E, EI, RD, RE] | |
defect | DefectCodec[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.
| Parameter | Type | Description |
|---|---|---|
value | Codec[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).
| Parameter | Type | Description |
|---|---|---|
value | Codec[A, I, RD, RE] | |
label | str | None = None | |
disallow_json_encode | bool = 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"]).
| Parameter | Type | Description |
|---|---|---|
success | Codec[A, AI, RD, RE] | |
failure | Codec[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>).
| Parameter | Type | Description |
|---|---|---|
guard | Callable[[object], TypeIs[T]] | |
annotations | object = {} |
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(...).
| Parameter | Type | Description |
|---|---|---|
type_parameters | Sequence[Codec[Any, Any, RD, RE]] | |
run | Callable[[tuple[Bottom[Any, Any, Never, Never], ...]], Parse[T]] | |
annotations | object = {} |
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.
| Parameter | Type | Description |
|---|---|---|
cls | type[T] | |
annotations | object = {} |
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).
| Parameter | Type | Description |
|---|---|---|
source | str | |
flags | str = '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).
| Parameter | Type | Description |
|---|---|---|
source | str | |
flags | str = 'u' | |
annotations | object = {} |
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) -> DefectSchemaA 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.
| Parameter | Type | Description |
|---|---|---|
include_stack | bool = False | |
exclude_cause | bool = 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.
| Parameter | Type | Description |
|---|---|---|
kind | K | |
node | Codec[N, NI, RD, RE] | |
edge | Codec[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.
| Parameter | Type | Description |
|---|---|---|
key | Codec[K, KI, RD, RE] | |
value | Codec[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.
| Parameter | Type | Description |
|---|---|---|
value | Codec[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).
| Parameter | Type | Description |
|---|---|---|
schema | Top | |
on_excess_property | OnExcessProperty = 'ignore' | |
generate_descriptions | bool = False | |
include_annotation_key | Callable[[str], bool] | None = None | |
reference_policy | ReferencePolicy | 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).
| Parameter | Type | Description |
|---|---|---|
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 |
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.
| Parameter | Type | Description |
|---|---|---|
enums | type[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.
| Parameter | Type | Description |
|---|---|---|
literal | L |
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.
| Parameter | Type | Description |
|---|---|---|
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.
| Parameter | Type | Description |
|---|---|---|
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) -> TA 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.
| Parameter | Type | Description |
|---|---|---|
ast | AST | |
input | object | |
options | ParseOptions | None | |
construct | Callable[[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).
| Parameter | Type | Description |
|---|---|---|
f | Callable[[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).
| Parameter | Type | Description |
|---|---|---|
f | Callable[[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).
| Parameter | Type | Description |
|---|---|---|
f | Callable[[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).
| Parameter | Type | Description |
|---|---|---|
f | Callable[[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.
| Parameter | Type | Description |
|---|---|---|
default | Effect[E, SchemaError, R] | |
encoding_strategy | EncodingStrategy = '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.
| Parameter | Type | Description |
|---|---|---|
default | Effect[E, SchemaError, R] | |
encoding_strategy | EncodingStrategy = '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).
| Parameter | Type | Description |
|---|---|---|
default | Effect[T, SchemaError, R] | |
encoding_strategy | EncodingStrategy = '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).
| Parameter | Type | Description |
|---|---|---|
default | Effect[T, SchemaError, R] | |
encoding_strategy | EncodingStrategy = '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) -> NoneRaise SchemaError unless input is a value of the schema's
decoded side.
| Parameter | Type | Description |
|---|---|---|
schema | Top | |
input | object |
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]]| Parameter | Type | Description |
|---|---|---|
schema | Codec[A, I, R, object] | |
options | Unpack[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]]| Parameter | Type | Description |
|---|---|---|
schema | Codec[A, I, Never, object] | |
options | Unpack[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]]| Parameter | Type | Description |
|---|---|---|
schema | Codec[A, I, Never, object] | |
options | Unpack[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).
| Parameter | Type | Description |
|---|---|---|
schema | Codec[A, I, Never, object] | |
options | Unpack[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]]| Parameter | Type | Description |
|---|---|---|
schema | Codec[A, I, Never, object] | |
options | Unpack[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]| Parameter | Type | Description |
|---|---|---|
schema | Codec[A, I, Never, object] | |
options | Unpack[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]]| Parameter | Type | Description |
|---|---|---|
schema | Codec[A, object, R, object] | |
options | Unpack[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]]| Parameter | Type | Description |
|---|---|---|
schema | Codec[A, object, Never, object] | |
options | Unpack[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]]| Parameter | Type | Description |
|---|---|---|
schema | Codec[A, object, Never, object] | |
options | Unpack[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).
| Parameter | Type | Description |
|---|---|---|
schema | Codec[A, object, Never, object] | |
options | Unpack[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]]| Parameter | Type | Description |
|---|---|---|
schema | Codec[A, object, Never, object] | |
options | Unpack[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]| Parameter | Type | Description |
|---|---|---|
schema | Codec[A, object, Never, object] | |
options | Unpack[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]]| Parameter | Type | Description |
|---|---|---|
schema | Codec[A, I, object, R] | |
options | Unpack[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]]| Parameter | Type | Description |
|---|---|---|
schema | Codec[A, I, object, Never] | |
options | Unpack[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]]| Parameter | Type | Description |
|---|---|---|
schema | Codec[A, I, object, Never] | |
options | Unpack[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).
| Parameter | Type | Description |
|---|---|---|
schema | Codec[A, I, object, Never] | |
options | Unpack[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]]| Parameter | Type | Description |
|---|---|---|
schema | Codec[A, I, object, Never] | |
options | Unpack[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]| Parameter | Type | Description |
|---|---|---|
schema | Codec[A, I, object, Never] | |
options | Unpack[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]]| Parameter | Type | Description |
|---|---|---|
schema | Codec[object, I, object, R] | |
options | Unpack[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]]| Parameter | Type | Description |
|---|---|---|
schema | Codec[object, I, object, Never] | |
options | Unpack[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]]| Parameter | Type | Description |
|---|---|---|
schema | Codec[object, I, object, Never] | |
options | Unpack[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).
| Parameter | Type | Description |
|---|---|---|
schema | Codec[object, I, object, Never] | |
options | Unpack[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]]| Parameter | Type | Description |
|---|---|---|
schema | Codec[object, I, object, Never] | |
options | Unpack[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]| Parameter | Type | Description |
|---|---|---|
schema | Codec[object, I, object, Never] | |
options | Unpack[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.
| Parameter | Type | Description |
|---|---|---|
schema | Codec[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 guardmake#
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.
| Parameter | Type | Description |
|---|---|---|
schema | Codec[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 constructmake_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).
| Parameter | Type | Description |
|---|---|---|
schema | Codec[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 constructmake_option#
make_option[A](schema) -> Parser[A, Option[A]]The schema's constructor giving Some or None (Effect's
SchemaParser.makeOption).
| Parameter | Type | Description |
|---|---|---|
schema | Codec[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 constructRecord#
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".
| Parameter | Type | Description |
|---|---|---|
key | Codec[K, KI, RD, RE] | |
value | Codec[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.
| Parameter | Type | Description |
|---|---|---|
brand | Brand[A, B] | |
identifier | str | 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).
| Parameter | Type | Description |
|---|---|---|
first | Check[T] | |
rest | Check[T] = () | |
annotations | object = {} |
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.
| Parameter | Type | Description |
|---|---|---|
guard | Callable[[A], TypeIs[B]] | |
annotations | object = {} |
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 | NoneThe annotations describing schema: its last check's when it has
checks, else its own; None without any.
| Parameter | Type | Description |
|---|---|---|
schema | Top |
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 | NoneThe annotations of the struct key or tuple element holding
schema (annotate_key); None without any (Effect's
resolveAnnotationsKey).
| Parameter | Type | Description |
|---|---|---|
schema | Top |
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_annotationsis_schema#
is_schema(value) -> TypeIs[Top]value is a schema object, a schema class, or a schema adapted to
Standard Schema.
| Parameter | Type | Description |
|---|---|---|
value | object |
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).
| Parameter | Type | Description |
|---|---|---|
schema | Codec[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).
| Parameter | Type | Description |
|---|---|---|
schema | Codec[T, E, Never, RE] | |
leaf_hook | LeafHook | None = None | |
check_hook | CheckHook | None = None | |
parse_options | ParseOptions | 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).
| Parameter | Type | Description |
|---|---|---|
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.
| Parameter | Type | Description |
|---|---|---|
schema | StructSchema[TD, RD, RE] | |
records | RecordSchema[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).
| Parameter | Type | Description |
|---|---|---|
f | Callable[[], 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) -> EncodeKeysThe 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.
| Parameter | Type | Description |
|---|---|---|
mapping | Mapping[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).
| Parameter | Type | Description |
|---|---|---|
typed_dict | type[TD] | |
derive | Mapping[str, Callable[[A], Option[object]]] | |
fields | Codec[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.
| Parameter | Type | Description |
|---|---|---|
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.
| Parameter | Type | Description |
|---|---|---|
cases | Codec[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).
| Parameter | Type | Description |
|---|---|---|
literal | L |
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) -> ToTaggedUnionThe 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).
| Parameter | Type | Description |
|---|---|---|
tag | str |
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 = ()) -> TemplateLiteralSchemaThe 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).
| Parameter | Type | Description |
|---|---|---|
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.
| Parameter | Type | Description |
|---|---|---|
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.
| Parameter | Type | Description |
|---|---|---|
schema | Codec[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.
| Parameter | Type | Description |
|---|---|---|
schema | Codec[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).
| Parameter | Type | Description |
|---|---|---|
schema | Codec[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.
| Parameter | Type | Description |
|---|---|---|
schema | Codec[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.
| Parameter | Type | Description |
|---|---|---|
schema | Codec[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.
| Parameter | Type | Description |
|---|---|---|
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 |
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).
| Parameter | Type | Description |
|---|---|---|
schema | Codec[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).
| Parameter | Type | Description |
|---|---|---|
schema | Codec[T, object, object, object] | |
on_before | OnBefore | 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.
| Parameter | Type | Description |
|---|---|---|
to | Codec[I, object, object, object] | |
transformation | Transformation[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 overrideto_codec_iso#
to_codec_iso[T](schema) -> Bottom[T, Any]| Parameter | Type | Description |
|---|---|---|
schema | Codec[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]| Parameter | Type | Description |
|---|---|---|
schema | Codec[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]| Parameter | Type | Description |
|---|---|---|
_ | 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]| Parameter | Type | Description |
|---|---|---|
_ | 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.
| Parameter | Type | Description |
|---|---|---|
schema | Codec[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).
| Parameter | Type | Description |
|---|---|---|
transformation | Transformation[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).
| Parameter | Type | Description |
|---|---|---|
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).
| Parameter | Type | Description |
|---|---|---|
transformation | Transformation[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).
| Parameter | Type | Description |
|---|---|---|
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).
| Parameter | Type | Description |
|---|---|---|
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#
link[T, M](encode_to, transformation) -> ast.LinkA 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.
| Parameter | Type | Description |
|---|---|---|
encode_to | Codec[M, object, object, object] | |
transformation | Transformation[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).
| Parameter | Type | Description |
|---|---|---|
schema | Codec[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).
| Parameter | Type | Description |
|---|---|---|
schema | Codec[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.
| Parameter | Type | Description |
|---|---|---|
node | Codec[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 schemaModules#
On This Page
Re-exportsValuesTypesClassesFunctionsArrayListNonEmptyArrayTupleTupleWithRestUniqueArrayoptional_keyis_finiteis_intis_int32is_multiple_ofis_uint32make_is_betweenmake_is_greater_thanmake_is_greater_than_or_equal_tomake_is_less_thanmake_is_less_than_or_equal_tomake_is_multiple_ofis_between_code_pointsis_between_lengthis_between_propertiesis_between_sizeis_max_code_pointsis_max_lengthis_max_propertiesis_max_sizeis_min_code_pointsis_min_lengthis_min_propertiesis_min_sizeis_non_emptyis_property_namesis_uniqueis_unique_keyis_asciiis_base64is_base64_urlis_capitalizedis_ending_withis_guidis_includingis_lowercasedis_patternis_starting_withis_string_big_intis_string_finiteis_trimmedis_ulidis_uncapitalizedis_uppercasedis_uuidclass_checkfieldnewArrayEnsureNullOrOptionFromNullOrOptionFromOptionalKeyOptionFromOptionalNullOrRedactedFromValuefrom_json_stringFrozenSetMaptagwith_constructor_defaultCauseCauseReasonExitOptionRedactedResultdeclaredeclare_constructorinstance_ofcompile_ecmais_ecma_patternDefectGraphHashMapHashSetto_json_schema_documentto_json_schema_multi_documentEnumLiteralLiteralsUnionmake_class_synccatch_decodingcatch_encodingmiddleware_decodingmiddleware_encodingwith_decoding_defaultwith_decoding_default_keywith_decoding_default_typewith_decoding_default_type_keyassertsdecode_effectdecode_exitdecode_optiondecode_promisedecode_resultdecode_syncdecode_unknown_effectdecode_unknown_exitdecode_unknown_optiondecode_unknown_promisedecode_unknown_resultdecode_unknown_syncencode_effectencode_exitencode_optionencode_promiseencode_resultencode_syncencode_unknown_effectencode_unknown_exitencode_unknown_optionencode_unknown_promiseencode_unknown_resultencode_unknown_syncis_makemake_effectmake_optionRecordfrom_brandmake_filter_grouprefineresolve_annotationsresolve_annotations_keyis_schemato_standard_json_schema_v1to_standard_schema_v1StructStructWithRestsuspendencode_keysextend_toTaggedStructTaggedUniontag_default_omitto_tagged_unionTemplateLiteralTemplateLiteralParserto_codec_array_from_singleto_codec_go_jsonto_codec_jsonto_codec_string_treeto_differ_json_patchto_encoder_xmlto_equivalenceto_formatteroverride_to_codec_isoto_codec_isoto_isoto_iso_focusto_iso_sourceto_strategydecodedecode_toencodeencode_tofliplinkto_encodedto_typeTreeModules