mypy icon indicating copy to clipboard operation
mypy copied to clipboard

Type error when extending List[Union[str, int]] with List[str] via generic function

Open fishikles opened this issue 3 years ago • 0 comments

Bug Report

To Reproduce Using python 3.8 and mypy 0.971

with the following setup:

from typing import List, TypeVar, Union

T = TypeVar("T")
def test(A:List[T], B:List[T]) -> List[T]:
    ret:List[T] = []
    ret.extend(A)
    ret.extend(B)
    return ret

A:List[int] = [1]
B:List[int] = [2]
C:List[str] = ["C"]
D:List[str] = ["D"]

result:List[Union[str, int]] = []

try to type to following:

result.extend(test(A,B))
result.extend(test(C,D))

Expected Behavior

I would have expected this to be correctly typed as all elements in lists A, B, C and D are valid in the result list.

In my testing I noticed that the following 2 examples work fine:

tmp1 = test(A,B)
result.extend(tmp1)
tmp2 = test(C,D)
result.extend(tmp2)

and

result.extend(A)
result.extend(C)

Which seems to indicate that my expectiation is correct.

Actual Behavior

mypy return a typing error:

$ mypy test.py 
test.py:16: error: Argument 1 to "test" has incompatible type "List[int]"; expected "List[Union[str, int]]"
test.py:16: note: "List" is invariant -- see https://mypy.readthedocs.io/en/stable/common_issues.html#variance
test.py:16: note: Consider using "Sequence" instead, which is covariant
test.py:16: error: Argument 2 to "test" has incompatible type "List[int]"; expected "List[Union[str, int]]"
test.py:17: error: Argument 1 to "test" has incompatible type "List[str]"; expected "List[Union[str, int]]"
test.py:17: note: "List" is invariant -- see https://mypy.readthedocs.io/en/stable/common_issues.html#variance
test.py:17: note: Consider using "Sequence" instead, which is covariant
test.py:17: error: Argument 2 to "test" has incompatible type "List[str]"; expected "List[Union[str, int]]"
Found 4 errors in 1 file (checked 1 source file)

Your Environment

  • Mypy version used: 0.971
  • Mypy command-line flags: None
  • Mypy configuration options from mypy.ini (and other config files): None
  • Python version used: 3.8
  • Operating system and version: Ubuntu-20.04

fishikles avatar Sep 20 '22 20:09 fishikles