Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -635,14 +635,14 @@ from expression import TaggedUnion, case, tag
class Rectangle:
width: float
length: float
tag: Literal["rectangle"] = tag("rectangle")
tag: Literal["rectangle"] = tag()


@final
@case
class Circle:
radius: float
tag: Literal["circle"] = tag("circle")
tag: Literal["circle"] = tag()


Shape: TypeAlias = TaggedUnion[Rectangle | Circle]
Expand All @@ -651,7 +651,9 @@ Shape: TypeAlias = TaggedUnion[Rectangle | Circle]

`@case` creates a frozen dataclass and rejects subclasses at runtime. Use `@final` to
make type checkers reject subclasses too. The literal `tag` is fixed by the declaration
and excluded from constructor arguments and positional patterns.
and excluded from constructor arguments and positional patterns. `tag()` takes its
value from the `Literal` annotation, so the string is written only once. This happens
when the class is declared, normally during module import, rather than per instance.

`Shape` is an annotation alias. Construct and match the case classes directly:

Expand Down
8 changes: 5 additions & 3 deletions README.py
Original file line number Diff line number Diff line change
Expand Up @@ -699,14 +699,14 @@ async def outer_option() -> AsyncGenerator[int, int]:
class Rectangle:
width: float
length: float
tag: Literal["rectangle"] = tag("rectangle")
tag: Literal["rectangle"] = tag()


@final
@case
class Circle:
radius: float
tag: Literal["circle"] = tag("circle")
tag: Literal["circle"] = tag()


Shape: TypeAlias = TaggedUnion[Rectangle | Circle]
Expand All @@ -716,7 +716,9 @@ class Circle:
"""
`@case` creates a frozen dataclass and rejects subclasses at runtime. Use `@final` to
make type checkers reject subclasses too. The literal `tag` is fixed by the declaration
and excluded from constructor arguments and positional patterns.
and excluded from constructor arguments and positional patterns. `tag()` takes its
value from the `Literal` annotation, so the string is written only once. This happens
when the class is declared, normally during module import, rather than per instance.

`Shape` is an annotation alias. Construct and match the case classes directly:
"""
Expand Down
10 changes: 5 additions & 5 deletions TAGGED_UNION_PROPOSAL.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,15 +45,15 @@ from expression import TaggedUnion, case, tag
@case
class Circle:
radius: float
tag: Literal["circle"] = tag("circle")
tag: Literal["circle"] = tag()


@final
@case
class Rectangle:
width: float
height: float
tag: Literal["rectangle"] = tag("rectangle")
tag: Literal["rectangle"] = tag()


Shape: TypeAlias = TaggedUnion[Circle | Rectangle]
Expand All @@ -75,7 +75,7 @@ The three helpers have distinct responsibilities:
| API | Responsibility |
|---|---|
| `@case` | Generate a frozen dataclass, validate the case declaration, and reject ordinary runtime subclassing. |
| `tag("circle")` | Define a fixed discriminator excluded from constructor arguments and positional class patterns. |
| `tag()` | Infer a fixed discriminator from the Literal annotation, excluded from constructor arguments and positional class patterns. |
| `TaggedUnion[Circle \| Rectangle]` | Keep the alternatives visible to checkers and attach metadata for optional Pydantic decoding. |

`@final` remains explicit because `dataclass_transform` describes fields and
Expand Down Expand Up @@ -134,13 +134,13 @@ T = TypeVar("T", covariant=True)
@case
class Some(Generic[T]):
some: T
tag: Literal["some"] = tag("some")
tag: Literal["some"] = tag()


@final
@case
class Nothing:
tag: Literal["none"] = tag("none")
tag: Literal["none"] = tag()


Option: TypeAlias = Annotated[
Expand Down
39 changes: 37 additions & 2 deletions docs/guides/domain-modeling.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,13 @@
@case
class Card:
last_four: str
tag: Literal["card"] = tag("card")
tag: Literal["card"] = tag()


@final
@case
class Cash:
tag: Literal["cash"] = tag("cash")
tag: Literal["cash"] = tag()


Payment: TypeAlias = TaggedUnion[Card | Cash]
Expand Down Expand Up @@ -53,3 +53,38 @@ def describe(payment: Payment) -> str:
alias grows. Use a standard enum when every alternative is just a named constant.
See [Tagged unions](reference_union) for serialization and the full API.
"""


# %% [markdown]
"""
## Single-case domain types

A case can also wrap a primitive value in a distinct domain type, similar to an F#
single-case discriminated union. The class itself serves as the type and constructor;
a separate union alias is unnecessary for ordinary domain use.
"""

# %%
@final
@case
class CustomerId:
value: int
tag: Literal["customer_id"] = tag()


def customer_number(customer_id: CustomerId) -> int:
match customer_id:
case CustomerId(value):
return value


assert customer_number(CustomerId(42)) == 42

# %% [markdown]
"""
The annotation keeps `CustomerId` distinct from an ordinary `int` during static
checking. `tag()` derives its fixed value from `Literal` when the class is declared,
normally during module import. Constructing instances does not repeat that inference.
For tagged Pydantic decoding, use `TypeAdapter(TaggedUnion[CustomerId])` at the
serialization boundary.
"""
13 changes: 7 additions & 6 deletions docs/guides/migration-major.md
Original file line number Diff line number Diff line change
Expand Up @@ -152,12 +152,12 @@ from expression import TaggedUnion, case, tag
@case
class Card:
last_four: str
tag: Literal["card"] = tag("card")
tag: Literal["card"] = tag()

@final
@case
class Cash:
tag: Literal["cash"] = tag("cash")
tag: Literal["cash"] = tag()

Payment: TypeAlias = TaggedUnion[Card | Cash]

Expand All @@ -172,8 +172,9 @@ def describe(payment: Payment) -> str:
Construct `Card("1234")` and `Cash()` directly. The alias is a closed list of
alternatives, not a class or a constructor namespace. `tagged_union` is now the
module namespace; its old decorator and the old `case()` field marker are
removed. The `tag` field is required and must declare one matching string literal.
It is excluded from construction and positional patterns. Use a class pattern or
removed. The `tag` field is required: write `tag: Literal["name"] = tag()` and
`@case` derives the value from the annotation. `tag()` no longer accepts an
explicit value argument. The tag is excluded from construction and positional patterns. Use a class pattern or
compare `.tag` to narrow the payload type.

`@case` generates a frozen dataclass and rejects runtime subclasses. Keep
Expand Down Expand Up @@ -217,13 +218,13 @@ from expression import TaggedUnion, case, tag
@final
@case
class Missing:
tag: Literal["missing"] = tag("missing")
tag: Literal["missing"] = tag()

@final
@case
class Found:
value: str
tag: Literal["found"] = tag("found")
tag: Literal["found"] = tag()

Lookup: TypeAlias = TaggedUnion[Found | Missing]
Missing_ = Missing() # Optional shared value to avoid repeated construction.
Expand Down
17 changes: 12 additions & 5 deletions docs/reference/union.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,14 @@ from expression import TaggedUnion, case, tag
@case
class Circle:
radius: float
tag: Literal["circle"] = tag("circle")
tag: Literal["circle"] = tag()

@final
@case
class Rectangle:
width: float
height: float
tag: Literal["rectangle"] = tag("rectangle")
tag: Literal["rectangle"] = tag()

Shape: TypeAlias = TaggedUnion[Circle | Rectangle]

Expand All @@ -47,12 +47,19 @@ narrows the value to that case. Each case has only its own payload fields.
dataclass equality, representation, copying, pickling, and hashing. Hashing
requires hashable payloads; ordering is not generated.

Every case declares one `tag: Literal["..."] = tag("...")`. Tags must be unique
within a union. The tag is excluded from the constructor, representation, and
positional patterns. Payloads use ordinary annotations and may have defaults
Every case declares one `tag: Literal["..."] = tag()`. The decorator derives the
tag value from its annotation; `tag()` does not accept a value argument.
Tags must be unique within a union. The tag is excluded from the constructor,
representation, and positional patterns. Payloads use ordinary annotations and may have defaults
or `dataclasses.field(default_factory=...)`. `InitVar` and payload fields with
`init=False` are not supported.

The annotation must contain exactly one string literal. Inference happens when
`@case` executes the class declaration, normally once during module import for
global cases. Instance construction, tag access, and pattern matching do not
repeat this work. A class declared inside a function is recreated each time
execution reaches its declaration.

Use `@case(kw_only=True)` for keyword-only payloads and `@case(repr=False)` when
providing a custom representation, for example to redact a password. A case
with no payload declares only its tag; separate instances compare equal but
Expand Down
4 changes: 2 additions & 2 deletions docs/tutorial/data_modelling.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,14 +22,14 @@ class Address:
@case
class Pickup:
store: str
tag: Literal["pickup"] = tag("pickup")
tag: Literal["pickup"] = tag()


@final
@case
class Shipping:
address: Address
tag: Literal["shipping"] = tag("shipping")
tag: Literal["shipping"] = tag()


Delivery: TypeAlias = TaggedUnion[Pickup | Shipping]
Expand Down
4 changes: 2 additions & 2 deletions expression/core/option.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ class Some(PipeMixin, Generic[_TSourceOut]):
"""An optional value that is present, including when its payload is None."""

some: _TSourceOut
tag: Literal["some"] = tag("some")
tag: Literal["some"] = tag()

def default_value(self, value: object) -> _TSourceOut:
"""Return the present value."""
Expand Down Expand Up @@ -160,7 +160,7 @@ class Nothing(PipeMixin):
instance. Use ``NOTHING`` to reuse it without calling the constructor.
"""

tag: Literal["none"] = tag("none")
tag: Literal["none"] = tag()
_instance: ClassVar[Nothing | None] = None

def __new__(cls) -> Nothing:
Expand Down
4 changes: 2 additions & 2 deletions expression/core/result.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ class Ok(PipeMixin, Generic[_T]):
"""A successful result containing a value."""

ok: _T
tag: Literal["ok"] = tag("ok")
tag: Literal["ok"] = tag()

def default_value(self, value: object) -> _T:
"""Return the successful value."""
Expand Down Expand Up @@ -145,7 +145,7 @@ class Error(PipeMixin, Generic[_E]):
"""A failed result containing an error."""

error: _E
tag: Literal["error"] = tag("error")
tag: Literal["error"] = tag()

def default_value(self, value: _U) -> _U:
"""Return the fallback value."""
Expand Down
43 changes: 32 additions & 11 deletions expression/core/tagged_union.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,16 @@

import sys
from collections.abc import Callable
from dataclasses import Field, dataclass, field, fields, is_dataclass
from dataclasses import MISSING, Field, dataclass, field, fields, is_dataclass
from inspect import currentframe, signature
from typing import (
Annotated,
Any,
Literal,
Protocol,
TypeAlias,
TypeVar,
cast,
dataclass_transform,
final,
get_args,
Expand All @@ -29,7 +31,6 @@


_T = TypeVar("_T")
_Tag = TypeVar("_Tag", bound=str)


class _TaggedCase(Protocol):
Expand All @@ -41,17 +42,15 @@ def tag(self) -> str: ...
TaggedUnion: TypeAlias = Annotated[_Case, UnionSchema()]


def tag(value: _Tag, *, init: Literal[False] = False, repr: bool = False) -> _Tag:
def tag(*, init: Literal[False] = False, repr: bool = False) -> Any:
"""Declare a fixed discriminator excluded from a case's constructor.

Annotate the field as ``tag: Literal['name'] = tag('name')``. The literal
remains visible to checkers, while construction cannot override its value.
Annotate the field as ``tag: Literal['name'] = tag()``. The case decorator
derives the default from the annotation. The ``init`` default tells static
dataclass checking to exclude the tag from construction; runtime fields
always use ``init=False``.
"""
if type(value) is not str:
raise TypeError("A case tag must be a string")
if init is not False:
raise TypeError("A case tag cannot be a constructor parameter")
return field(default=value, init=False, repr=repr, metadata={"expression.tag": True})
return field(init=False, repr=repr, metadata={"expression.tag": True})


@overload
Expand Down Expand Up @@ -82,6 +81,7 @@ def apply(cls: type[_T], namespace: dict[str, object]) -> type[_T]:
raise TypeError("@case requires a new class without a dataclass or case base")
if "__init__" in vars(cls):
raise TypeError("@case generates __init__; use __post_init__ for payload checks")
_infer_tag_default(cls, namespace)
transformed = dataclass(cls, frozen=True, repr=repr, kw_only=kw_only)
_validate_case(transformed, namespace)
config = dict(getattr(transformed, "__pydantic_config__", {}))
Expand All @@ -93,6 +93,27 @@ def apply(cls: type[_T], namespace: dict[str, object]) -> type[_T]:
return transform if _cls is None else apply(_cls, _declaration_namespace())


def _infer_tag_default(cls: type[object], namespace: dict[str, object]) -> None:
discriminator = vars(cls).get("tag")
if not isinstance(discriminator, Field) or not discriminator.metadata.get("expression.tag"):
return
discriminator = cast(Field[object], discriminator)
if discriminator.default is not MISSING:
return
if sys.version_info >= (3, 14):
from annotationlib import Format, get_annotations

annotations = get_annotations(cls, format=Format.STRING)
else:
annotations = vars(cls).get("__annotations__", {})
annotation = annotations.get("tag")
literal = _resolve_tag_annotation(cls, annotation, namespace)
values = get_args(literal)
if get_origin(literal) is not Literal or len(values) != 1 or type(values[0]) is not str:
raise TypeError("An inferred case tag must declare a single string Literal")
discriminator.default = values[0]


def _declaration_namespace() -> dict[str, object]:
# Resolve postponed tag annotations at the decorator call site, including
# function-local imports and aliases. Copy locals without retaining frames.
Expand Down Expand Up @@ -129,7 +150,7 @@ def _case_discriminator(
) -> Field[object]:
discriminator = next((item for item in declared if item.name == "tag"), None)
if discriminator is None or discriminator.init or not discriminator.metadata.get("expression.tag"):
raise TypeError("A case must declare tag: Literal['name'] = tag('name')")
raise TypeError("A case must declare tag: Literal['name'] = tag()")
literal = _resolve_tag_annotation(cls, discriminator.type, namespace)
if get_origin(literal) is not Literal or get_args(literal) != (discriminator.default,):
raise TypeError("The tag annotation must be a single Literal matching its tag() value")
Expand Down
Loading
Loading