mypy icon indicating copy to clipboard operation
mypy copied to clipboard

Narrow individual items when matching a tuple to a sequence pattern

Open loic-simon opened this issue 1 year ago • 1 comments

Fixes #12364

When matching a tuple to a sequence pattern, this change narrows the type of tuple items inside the matched case:

def test(a: bool, b: bool) -> None:
    match a, b:
        case True, True:
            reveal_type(a)  # before: "builtins.bool", after: "Literal[True]"

This also works with nested tuples, recursively:

def test(a: bool, b: bool, c: bool) -> None:
    match a, (b, c):
        case _, [True, False]:
            reveal_type(c)  # before: "builtins.bool", after: "Literal[False]"

This only partially fixes issue #12364; see my comment there for more context.


This is my first contribution to mypy, so I may miss some context or conventions; I'm eager for any feedback!

loic-simon avatar Feb 11 '24 14:02 loic-simon

According to mypy_primer, this change doesn't affect type check results on a corpus of open source code. ✅

github-actions[bot] avatar Feb 11 '24 15:02 github-actions[bot]

According to mypy_primer, this change doesn't affect type check results on a corpus of open source code. ✅

github-actions[bot] avatar Apr 02 '24 19:04 github-actions[bot]