Skip to content

Union[List[T], T] is not recognized by mypy #13792

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

Open
arogozhnikov opened this issue Oct 3, 2022 · 3 comments
Open

Union[List[T], T] is not recognized by mypy #13792

arogozhnikov opened this issue Oct 3, 2022 · 3 comments
Labels
bug mypy got something wrong

Comments

@arogozhnikov
Copy link

Bug Report

Union[List[T], T] is not recognized by mypy

To Reproduce

from typing import List, Union, TypeVar

T = TypeVar('T')


def first_or_only(x: Union[List[T], T]) -> T:
    pass

x1: int = first_or_only(1)
x2: int = first_or_only([1, 2, 3])
x3: tuple = first_or_only((1, 2, 3))

Expected Behavior

  1. x1 should be inferenced as int
  2. x2 should be inferenced as a) perfect case: int b) correct case int or list[int]
  3. x3 should be inferenced as tuple[int]

Both vs code and pycharm inference as 1 + 2a + 3.

Actual Behavior

Mypy output for the example above makes no sense to me:

error: Argument 1 to "first_or_only" has incompatible type "List[int]"; expected "List[<nothing>]"
Found 1 error in 1 file (checked 1 source file)

Your Environment

  • Mypy version used: 0.971
  • Mypy command-line flags: just file
  • Mypy configuration options from mypy.ini (and other config files): none
  • Python version used: 3.10
@arogozhnikov arogozhnikov added the bug mypy got something wrong label Oct 3, 2022
@tmke8
Copy link
Contributor

tmke8 commented Oct 5, 2022

Relevant: #11149

@AmberAnsari89
Copy link

Can I check this issue..i am beginner in open source contribution however I can analyse it for further clarity .please input your suggestion ..

@EzR1d3r
Copy link

EzR1d3r commented Jan 24, 2023

I guess the same issue with

from typing import TypeVar

StdPrimitiveType = TypeVar("StdPrimitiveType", int, float, str, bool)

def foo(val: StdPrimitiveType | set[StdPrimitiveType]):
    pass

foo({"a", "b"})

error: Argument 1 has incompatible type "Set[str]"; expected "Union[bool, Set[bool]]" [arg-type]

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

4 participants