Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unpacking doesn't do proper type narrowing #17240

Open
RbCaVi opened this issue May 14, 2024 · 1 comment
Open

Unpacking doesn't do proper type narrowing #17240

RbCaVi opened this issue May 14, 2024 · 1 comment
Labels
bug mypy got something wrong

Comments

@RbCaVi
Copy link

RbCaVi commented May 14, 2024

Bug Report

When you unpack a tuple with a union type after an if statement that causes narrowing, the unpacked elements have a different type than the elements of the tuple.

To Reproduce

Playground

Expected Behavior

I expected the revealed types of x[0] and y to be the same as each other in all three cases.

Actual Behavior

../test.py:9: note: Revealed type is "Union[tuple[builtins.int], tuple[builtins.float]]"
../test.py:10: note: Revealed type is "builtins.float"
../test.py:11: note: Revealed type is "Union[builtins.int, builtins.float]"

../test.py:20: note: Revealed type is "Union[tuple[Literal['X']], tuple[test.S]]"
../test.py:21: note: Revealed type is "test.S"
../test.py:22: note: Revealed type is "Union[Literal['X'], test.S]"

../test.py:30: note: Revealed type is "tuple[Union[Literal['X'], test.S]]"
../test.py:31: note: Revealed type is "test.S"
../test.py:32: note: Revealed type is "Union[Literal['X'], test.S]"

Your Environment

  • Mypy version used: Github (mypy 1.11.0+dev.35fbd2a852be2c47e8006429afe9b3ad4b1bfac2 (compiled: no))
  • Mypy command-line flags: none
  • Mypy configuration options from mypy.ini (and other config files): none
  • Python version used: 3.12
@RbCaVi RbCaVi added the bug mypy got something wrong label May 14, 2024
@rtumin2
Copy link

rtumin2 commented Sep 11, 2024

I believe this is another example

from typing import Union

my_type = Union[
    tuple[float, None],
    tuple[None, float],
]


def f(x: my_type):
    a, b = x
    if a is not None:
        return a*2
    else:
        return b*2

This gives

test.py:14: error: Unsupported operand types for * ("None" and "int")  [operator]
test.py:14: note: Left operand is of type "float | None"

Compare to the following, in which the false positive does not occur:

from typing import Union

my_type = Union[
    tuple[float, None],
    tuple[None, float],
]


def f(x: my_type):
    if x[0] is not None:
        return x[0]*2
    else:
        return x[1]*2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug mypy got something wrong
Projects
None yet
Development

No branches or pull requests

2 participants