pyright icon indicating copy to clipboard operation
pyright copied to clipboard

Use match case guard to narrow else cases

Open cdce8p opened this issue 6 months ago • 0 comments

Is your feature request related to a problem? Please describe.

def f(var: str | bool | None) -> None:
    match var:
        case _ if not var:
            reveal_type(var)
        case _:
            reveal_type(var)  # can be narrowed to: str | Literal[True]

The case guard if not var can be used to narrow var for the else case. This works in mypy v1.17.1 and it would be great if pyright could support it as well.

The logic seems to be partially implemented already. E.g. with just patterns the else case is narrowed correctly.

def f(var: str | bool | None) -> None:
    match var:
        case None:
            reveal_type(var)
        case _:
            reveal_type(var)  # str | bool

-- pyright 1.1.404

cdce8p avatar Aug 27 '25 12:08 cdce8p