-
-
Notifications
You must be signed in to change notification settings - Fork 32.6k
Closed as not planned
Labels
type-featureA feature request or enhancementA feature request or enhancement
Description
Feature or enhancement
Proposal:
New-style unions can already be used in isinstance
. It would be nice if they could also be used as match patterns:
IntOrStr = int | str
x = 0
assert isinstance(x, IntOrStr) # works
match x:
case IntOrStr(): # E: "called match pattern must be a type"
print(f"x is an int or str: {x}")
This would make implementing sum types much nicer:
from typing import NamedTuple
class ColorName(NamedTuple):
name: str
class RGB(NamedTuple):
r: int
g: int
b: int
Color = ColorName | RGB
def f(color: Color): ...
c: Color = RGB(0, 255, 128)
def g(color: Color | str):
match c:
case Color():
f(c)
case str():
f(ColorName(c))
Has this already been discussed elsewhere?
I have already discussed this feature proposal on Discourse
Links to previous discussion of this feature:
A more dramatic proposal was discussed here, but there was no consensus:
https://discuss.python.org/t/syntactic-sugar-for-union-cases-in-match-statements/49274
This is a significantly reduced proposal now.
Linked PRs
Metadata
Metadata
Assignees
Labels
type-featureA feature request or enhancementA feature request or enhancement