Syntactic sugar for union cases in match statements

14 posts were merged into an existing topic: A small implementation of Algebaric Data Types

If anyone wants to play around with the proposal, I have a prototype implementation here: GitHub - tmke8/cpython at union-match-args It’s absolutely not ready to be submitted as a PR, but it works:

Python 3.13.0a5+ (heads/union-match-args:7524bcf619, Apr  4 2024, 13:46:50) [GCC 13.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from collections import namedtuple
>>> A = namedtuple('A', ['x'])
>>> B = namedtuple('B', ['x', 'y'])
>>> AB = A | B
>>> AB.__match_args__
('x',)
>>> ab = A(0)
>>> match ab:
...   case AB(x):
...     print(f"AB({x})")
...
AB(0)

Showing nice error messages turned out to be quite tricky though, so maybe this isn’t the right proposal after all.

1 Like

To clarify, TaggedUnion is a sum of TypeA and TypeB, not of TagA or TagB. The union of two distinct wrapper types is a proper sum. T2 = TagA | TagA would not be a true sum, as there’s no way to distinguish between “left” and “right” TypeA values.

1 Like