Skip to content

Allow unions as simple match patterns #118524

@tmke8

Description

@tmke8

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

No one assigned

    Labels

    type-featureA feature request or enhancement

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions