From a9204fbc5a9826e26e9598ba92eb8f71b4456253 Mon Sep 17 00:00:00 2001 From: Dag Brattli Date: Thu, 12 Nov 2026 02:00:48 +0100 Subject: [PATCH] feat!: infer union tags from literal annotations --- README.md | 8 +-- README.py | 8 +-- TAGGED_UNION_PROPOSAL.md | 10 ++-- docs/guides/domain-modeling.py | 39 +++++++++++++- docs/guides/migration-major.md | 13 ++--- docs/reference/union.md | 17 +++++-- docs/tutorial/data_modelling.py | 4 +- expression/core/option.py | 4 +- expression/core/result.py | 4 +- expression/core/tagged_union.py | 43 ++++++++++++---- tests/test_parser.py | 8 +-- tests/test_tagged_union.py | 90 ++++++++++++++++++++++++--------- tests/test_union_schema.py | 18 +++---- tests/typing_contracts.py | 14 ++--- typing_tests/negative.py | 10 ++-- 15 files changed, 200 insertions(+), 90 deletions(-) diff --git a/README.md b/README.md index acbd6e10..ae2f1836 100644 --- a/README.md +++ b/README.md @@ -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] @@ -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: diff --git a/README.py b/README.py index eae86e41..1ab0ae8e 100644 --- a/README.py +++ b/README.py @@ -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] @@ -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: """ diff --git a/TAGGED_UNION_PROPOSAL.md b/TAGGED_UNION_PROPOSAL.md index 101e7094..0d03dd5c 100644 --- a/TAGGED_UNION_PROPOSAL.md +++ b/TAGGED_UNION_PROPOSAL.md @@ -45,7 +45,7 @@ from expression import TaggedUnion, case, tag @case class Circle: radius: float - tag: Literal["circle"] = tag("circle") + tag: Literal["circle"] = tag() @final @@ -53,7 +53,7 @@ class Circle: class Rectangle: width: float height: float - tag: Literal["rectangle"] = tag("rectangle") + tag: Literal["rectangle"] = tag() Shape: TypeAlias = TaggedUnion[Circle | Rectangle] @@ -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 @@ -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[ diff --git a/docs/guides/domain-modeling.py b/docs/guides/domain-modeling.py index ae7d77b9..8d85afa6 100644 --- a/docs/guides/domain-modeling.py +++ b/docs/guides/domain-modeling.py @@ -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] @@ -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. +""" diff --git a/docs/guides/migration-major.md b/docs/guides/migration-major.md index 19bfe405..cf0cd8b6 100644 --- a/docs/guides/migration-major.md +++ b/docs/guides/migration-major.md @@ -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] @@ -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 @@ -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. diff --git a/docs/reference/union.md b/docs/reference/union.md index 28d7093b..591bd968 100644 --- a/docs/reference/union.md +++ b/docs/reference/union.md @@ -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] @@ -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 diff --git a/docs/tutorial/data_modelling.py b/docs/tutorial/data_modelling.py index 5ed7c09f..9cf9922a 100644 --- a/docs/tutorial/data_modelling.py +++ b/docs/tutorial/data_modelling.py @@ -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] diff --git a/expression/core/option.py b/expression/core/option.py index c1500bb5..1c6e44c7 100644 --- a/expression/core/option.py +++ b/expression/core/option.py @@ -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.""" @@ -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: diff --git a/expression/core/result.py b/expression/core/result.py index abfe74b1..ce1a36d7 100644 --- a/expression/core/result.py +++ b/expression/core/result.py @@ -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.""" @@ -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.""" diff --git a/expression/core/tagged_union.py b/expression/core/tagged_union.py index 65cb81a8..d69f7823 100644 --- a/expression/core/tagged_union.py +++ b/expression/core/tagged_union.py @@ -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, @@ -29,7 +31,6 @@ _T = TypeVar("_T") -_Tag = TypeVar("_Tag", bound=str) class _TaggedCase(Protocol): @@ -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 @@ -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__", {})) @@ -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. @@ -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") diff --git a/tests/test_parser.py b/tests/test_parser.py index e265676b..0affb38a 100644 --- a/tests/test_parser.py +++ b/tests/test_parser.py @@ -182,28 +182,28 @@ class Compare: left: Expression comparators: Block[Expression] ops: Block[ComparisonOperator] - tag: Literal["compare"] = tag("compare") + tag: Literal["compare"] = tag() @final @case class Name: name: str - tag: Literal["name"] = tag("name") + tag: Literal["name"] = tag() @final @case class Constant: value: object - tag: Literal["constant"] = tag("constant") + tag: Literal["constant"] = tag() @final @case class Boolean: operator: BoolOp - tag: Literal["boolean"] = tag("boolean") + tag: Literal["boolean"] = tag() Expression: TypeAlias = TaggedUnion[Name | Constant | Boolean | Compare] diff --git a/tests/test_tagged_union.py b/tests/test_tagged_union.py index 31cea786..204672aa 100644 --- a/tests/test_tagged_union.py +++ b/tests/test_tagged_union.py @@ -21,7 +21,7 @@ @case class Circle: radius: float - tag: Literal["circle"] = tag("circle") + tag: Literal["circle"] = tag() def area(self) -> float: return 3.14159 * self.radius**2 @@ -32,7 +32,7 @@ def area(self) -> float: class Rectangle: width: float height: float - tag: Literal["rectangle"] = tag("rectangle") + tag: Literal["rectangle"] = tag() def area(self) -> float: return self.width * self.height @@ -45,13 +45,13 @@ def area(self) -> float: @case class Just(Generic[_T]): value: _T - tag: Literal["just"] = tag("just") + tag: Literal["just"] = tag() @final @case class Missing: - tag: Literal["missing"] = tag("missing") + tag: Literal["missing"] = tag() Maybe: TypeAlias = TaggedUnion[Just[_T] | Missing] @@ -64,14 +64,14 @@ class Missing: class Folder: name: str children: tuple[Tree, ...] - tag: Literal["folder"] = tag("folder") + tag: Literal["folder"] = tag() @final @case class Leaf: name: str - tag: Literal["leaf"] = tag("leaf") + tag: Literal["leaf"] = tag() Tree: TypeAlias = TaggedUnion[Folder | Leaf] @@ -83,7 +83,7 @@ class Request: path: str retries: int = 3 headers: dict[str, str] = field(default_factory=dict[str, str]) - tag: Literal["request"] = tag("request") + tag: Literal["request"] = tag() @final @@ -91,14 +91,14 @@ class Request: class Labelled: number: int label: str = field(default="", kw_only=True) - tag: Literal["labelled"] = tag("labelled") + tag: Literal["labelled"] = tag() @final @case(repr=False) class SecurePassword: password: str - tag: Literal["password"] = tag("password") + tag: Literal["password"] = tag() def __repr__(self) -> str: return "SecurePassword('********')" @@ -261,7 +261,7 @@ def description(self) -> str: @case class Positive(Named): value: int - tag: Literal["positive"] = tag("positive") + tag: Literal["positive"] = tag() def __post_init__(self) -> None: if self.value <= 0: @@ -280,15 +280,17 @@ def _declaration(annotations: dict[str, object], attributes: dict[str, object]) ("annotations", "attributes"), [ ({"value": int}, {}), + ({}, {"tag": tag()}), + ({"tag": str}, {"tag": tag()}), + ({"tag": Literal["x", "y"]}, {"tag": tag()}), + ({"tag": Literal[1]}, {"tag": tag()}), + ({"tag": ClassVar[Literal["x"]]}, {"tag": tag()}), + ({"tag": "Literal[missing]"}, {"tag": tag()}), ({"tag": Literal["x"]}, {"tag": "x"}), ({"tag": Literal["x"]}, {"tag": field(default="x", init=False)}), - ({"tag": Literal["x"]}, {"tag": tag("y")}), - ({"tag": str}, {"tag": tag("x")}), - ({"tag": Literal["x", "y"]}, {"tag": tag("x")}), - ({"tag": ClassVar[Literal["x"]]}, {"tag": tag("x")}), - ({"tag": Literal["x"], "value": int}, {"tag": tag("x"), "value": field(default=1, init=False)}), - ({"tag": Literal["x"], "value": InitVar[int]}, {"tag": tag("x")}), - ({"tag": Literal["x"], "other": str}, {"tag": tag("x"), "other": tag("other")}), + ({"tag": Literal["x"], "value": int}, {"tag": tag(), "value": field(default=1, init=False)}), + ({"tag": Literal["x"], "value": InitVar[int]}, {"tag": tag()}), + ({"tag": Literal["x"], "other": str}, {"tag": tag(), "other": tag()}), ], ) def test_invalid_case_declarations_are_rejected(annotations: dict[str, object], attributes: dict[str, object]): @@ -300,7 +302,7 @@ def test_already_decorated_dataclasses_are_rejected(): @dataclass class Existing: value: int - tag: Literal["existing"] = tag("existing") + tag: Literal["existing"] = tag() with pytest.raises(TypeError): case(Existing) @@ -314,7 +316,7 @@ class Existing: value: int class Inherited(Existing): - tag: Literal["inherited"] = tag("inherited") + tag: Literal["inherited"] = tag() with pytest.raises(TypeError): case(Inherited) @@ -323,7 +325,7 @@ class Inherited(Existing): def test_custom_init_is_rejected(): class Custom: value: int - tag: Literal["custom"] = tag("custom") + tag: Literal["custom"] = tag() def __init__(self, value: int) -> None: self.value = value @@ -339,7 +341,7 @@ def test_local_literal_import_resolves_with_bare_case_decorator(): @case class Local: value: int - tag: L["local"] = tag("local") + tag: L["local"] = tag() assert Local(42).tag == "local" @@ -351,7 +353,7 @@ def test_local_literal_import_resolves_with_case_decorator_factory(): @case() class Local: value: int - tag: L["local"] = tag("local") + tag: L["local"] = tag() assert Local(42).tag == "local" @@ -365,7 +367,7 @@ def first() -> object: @final @decorate class First: - tag: L["first"] = tag("first") + tag: L["first"] = tag() return First() @@ -375,9 +377,49 @@ def second() -> object: @final @decorate class Second: - tag: L["second"] = tag("second") + tag: L["second"] = tag() return Second() assert getattr(first(), "tag") == "first" assert getattr(second(), "tag") == "second" + + +def test_inferred_tag_precedes_payload_and_keeps_dataclass_contract(): + @final + @case + class Identifier: + tag: Literal["identifier"] = tag(repr=True) + value: int + + identifier = Identifier(42) + assert_type(identifier.tag, Literal["identifier"]) + assert identifier.tag == "identifier" + assert Identifier.tag == "identifier" + assert fields(Identifier)[0].default == "identifier" + assert Identifier.__match_args__ == ("value",) + assert asdict(identifier) == {"tag": "identifier", "value": 42} + assert repr(identifier).endswith("Identifier(tag='identifier', value=42)") + + +def test_inferred_tag_without_postponed_annotations(): + namespace: dict[str, Any] = {"__name__": __name__} + source = """ +from typing import Literal +from expression import case, tag + +@case +class Identifier: + value: int + tag: Literal["identifier"] = tag() +""" + exec(compile(source, "", "exec", dont_inherit=True), namespace) + identifier = namespace["Identifier"](42) + assert identifier.tag == "identifier" + assert asdict(identifier) == {"value": 42, "tag": "identifier"} + + +def test_tag_rejects_explicit_value_argument(): + dynamic_tag: Any = tag + with pytest.raises(TypeError): + dynamic_tag("explicit") diff --git a/tests/test_union_schema.py b/tests/test_union_schema.py index e53ec980..088be506 100644 --- a/tests/test_union_schema.py +++ b/tests/test_union_schema.py @@ -122,7 +122,7 @@ class MixedModel(BaseModel): @case class SchemaCircle: radius: Annotated[float, Field(gt=0)] - tag: Literal["circle"] = tag("circle") + tag: Literal["circle"] = tag() @final @@ -133,7 +133,7 @@ class SchemaRectangle: width: float height: float label: str = "rectangle" - tag: Literal["rectangle"] = tag("rectangle") + tag: Literal["rectangle"] = tag() _SchemaValue = TypeVar("_SchemaValue") @@ -144,14 +144,14 @@ class SchemaRectangle: class SchemaBox(Generic[_SchemaValue]): value: _SchemaValue notes: list[str] = field(default_factory=list[str]) - tag: Literal["box"] = tag("box") + tag: Literal["box"] = tag() @final @case class SchemaUnit: initialized: ClassVar[list[str]] = [] - tag: Literal["unit"] = tag("unit") + tag: Literal["unit"] = tag() def __post_init__(self) -> None: self.initialized.append("unit") @@ -221,14 +221,14 @@ def test_nested_tagged_union_aliases_flatten_and_keep_canonical_units(): @case class SchemaLeaf: value: int - tag: Literal["leaf"] = tag("leaf") + tag: Literal["leaf"] = tag() @final @case class SchemaBranch: children: list[TaggedUnion[SchemaLeaf | SchemaBranch]] - tag: Literal["branch"] = tag("branch") + tag: Literal["branch"] = tag() def test_recursive_custom_cases_validate_and_preserve_schema_references(): @@ -299,7 +299,7 @@ def test_union_rejects_duplicate_tags_and_noncase_members(): @case class OtherCircle: diameter: float - tag: Literal["circle"] = tag("circle") + tag: Literal["circle"] = tag() @dataclass(frozen=True) class PlainDataclass: @@ -319,14 +319,14 @@ class PlainDataclass: @case class SchemaAliased: value: Annotated[int, Field(alias="wire_value")] - tag: Literal["aliased"] = tag("aliased") + tag: Literal["aliased"] = tag() @final @case class SchemaSerializationAlias: value: Annotated[int, Field(serialization_alias="wire_value")] - tag: Literal["serialization_alias"] = tag("serialization_alias") + tag: Literal["serialization_alias"] = tag() @pytest.mark.parametrize("case_type", [SchemaAliased, SchemaSerializationAlias]) diff --git a/tests/typing_contracts.py b/tests/typing_contracts.py index 6fb7c606..3eff5671 100644 --- a/tests/typing_contracts.py +++ b/tests/typing_contracts.py @@ -70,7 +70,7 @@ def result_contract(value: Result[int, str]) -> None: @case class Circle: radius: float - tag: Literal["circle"] = tag("circle") + tag: Literal["circle"] = tag() @final @@ -79,7 +79,7 @@ class Rectangle: width: float height: float label: str = field(default="", kw_only=True) - tag: Literal["rectangle"] = tag("rectangle") + tag: Literal["rectangle"] = tag() Shape: TypeAlias = TaggedUnion[Circle | Rectangle] @@ -89,13 +89,13 @@ class Rectangle: @case class Just(Generic[_T]): value: _T - tag: Literal["just"] = tag("just") + tag: Literal["just"] = tag() @final @case class Missing: - tag: Literal["missing"] = tag("missing") + tag: Literal["missing"] = tag() Maybe: TypeAlias = TaggedUnion[Just[_T] | Missing] @@ -106,7 +106,7 @@ class Missing: class Request: path: str retries: int = 3 - tag: Literal["request"] = tag("request") + tag: Literal["request"] = tag() def custom_case_construction() -> None: @@ -154,14 +154,14 @@ def custom_tag_narrowing(value: Maybe[int]) -> int: @case class Branch: children: tuple[Tree, ...] - tag: Literal["branch"] = tag("branch") + tag: Literal["branch"] = tag() @final @case class Leaf: value: int - tag: Literal["leaf"] = tag("leaf") + tag: Literal["leaf"] = tag() Tree: TypeAlias = TaggedUnion[Branch | Leaf] diff --git a/typing_tests/negative.py b/typing_tests/negative.py index ed948517..2ea48a18 100644 --- a/typing_tests/negative.py +++ b/typing_tests/negative.py @@ -44,13 +44,13 @@ class Extra(Some[int]): # type-error @case class CustomValue(Generic[_T]): value: _T - tag: Literal["value"] = tag("value") + tag: Literal["value"] = tag() @final @case class CustomEmpty: - tag: Literal["empty"] = tag("empty") + tag: Literal["empty"] = tag() Custom: TypeAlias = TaggedUnion[CustomValue[_T] | CustomEmpty] @@ -89,15 +89,15 @@ class CustomExtra(CustomValue[int]): # type-error @final @case -class CustomWrongDeclaration: - tag: Literal["expected"] = tag("different") # type-error +class CustomExplicitTag: + tag: Literal["explicit"] = tag("explicit") # type-error @final @case(kw_only=True) class CustomKeyword: value: int - tag: Literal["keyword"] = tag("keyword") + tag: Literal["keyword"] = tag() custom_positional_keyword_only = CustomKeyword(1) # type-error