mypy icon indicating copy to clipboard operation
mypy copied to clipboard

assert_never on exclusive union of tuples (type narrowing issue?)

Open hjwp opened this issue 1 year ago • 4 comments

I feel like this code should work but it doesn't. Am I missing something?

from typing_extensions import assert_never

class Left1:
    pass
class Left2:
    pass

class Right1:
    pass
class Right2:
    pass

# this function should take either left1+right1, or left2+right2

def foo(pair: tuple[Left1, Right1] | tuple[Left2, Right2]) -> str:
    match thing:
        case (Left1(), Right1()):
            return "1"
        case (Left2(), Right2()):
            return "2"
        case _:
            # at this point, we should have exhausted both possibilities in the union.
            assert_never(pair)

gives

src/pairs.py:27: error: Argument 1 to "assert_never" has incompatible type "Union[Tuple[Left1, Right1], Tuple[Left2, Right2]]"; expected "NoReturn"  [arg-type]

hjwp avatar Jan 29 '24 17:01 hjwp

This should be reported to your type checker (probably mypy); it's not an issue with typing-extensions which just provides the runtime version of assert_never.

I'll transfer the issue to mypy as I don't recall seeing it before.

JelleZijlstra avatar Jan 29 '24 17:01 JelleZijlstra

thanks very much for transferring! I didn't realise you could do that. much appreciated :)

hjwp avatar Jan 29 '24 23:01 hjwp

This seems like a duplicate of #15190

Hnasar avatar Jan 30 '24 23:01 Hnasar

It's similar but unlike #15190 this one doesn't involve Literal.

JelleZijlstra avatar Jan 30 '24 23:01 JelleZijlstra