Skip to content

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

Open
@arogozhnikov

Description

@arogozhnikov

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrong

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions