Skip to content

Inconsistent type inference with Union[List[int], T] context #3506

Open

Description

@JukkaL

Mypy behaves unexpectedly when caller provides a list expression that has non-int items to a function that accepts Union[List[int], T]:

from typing import *
T = TypeVar('T')
def f(a: Union[List[int], T]) -> T: pass
f([1])  # OK
f([''])  # E: List item 0 has incompatible type "str"   <<--- unexpected
a = ['']
f(a)  # OK

It would be better if mypy would always recognize that List[str] is a valid argument for f. However, if given a [] argument the inferred return type should be List[int].

This was originally discussed at #3501 (comment).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugtopic-union-types

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions