You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Type narrowing discards tuple from Union[Tuple, Sequence] in conditional #13749
When refining an element of type Union[Tuple, Sequence] with the isinstance(x, Sequence) in a conditional, the Tuple part of the type is wrongly discarded in the branch.
To Reproduce
fromtypingimportSequence, Tuple, Uniondeftest_func(x: Union[Tuple[int], Sequence[str]]) ->str:
ifisinstance(x, Sequence):
reveal_type(x) # Revealed type is "typing.Sequence[builtins.str]"returnx[0] # raises no errorreturn"a"# Statement is unreachable
Expected Behavior
The revealed type of x should be Union[Tuple[int], Sequence[str]] or something equivalent. The line return x[0] should be marked as an issue, because currently test_func((1,)) returns 1 so the functions shouldn't typecheck.
Actual Behavior
test.py:6:21: note: Revealed type is "typing.Sequence[builtins.str]"
test.py:8:5: error: Statement is unreachable [unreachable]
Found 1 error in 1 file (checked 1 source file)
Activity
brianschubert commentedon Dec 7, 2024
This was fixed in #16470, released with v1.8.0. Mypy now correctly infers a union type inside the if branch:
Thanks for the original report!