mypy complains about list of tuples when the tuple element types are defined

42 Views Asked by At

I have this code:

def foo(data: list[tuple[int, ...]]) -> None:
    pass


r = [(1, 2, 3)]
foo(r)

Checking with mypy 1.8.0 results in an error:

main.py:6: error: Argument 1 to "foo" has incompatible type "list[tuple[int, int, int]]"; expected "list[tuple[int, ...]]"  [arg-type]
main.py:6: note: "List" is invariant -- see https://mypy.readthedocs.io/en/stable/common_issues.html#variance
main.py:6: note: Consider using "Sequence" instead, which is covariant
Found 1 error in 1 file (checked 1 source file)

I would expect that type list[tuple[int, int, int]] would match a type hint defined as list[tuple[int, ...]]

Interestingly enough, it works if it is not inside a list:

def foo(data: tuple[int, ...]) -> None:
    pass


r = (1, 2, 3)
foo(r)

Results in:

Success: no issues found in 1 source file

It also works if I use a Sequence type instead of list:

from typing import Sequence

def foo(data: Sequence[tuple[int, ...]]) -> None:
    pass


r = [(1, 2, 3)]
foo(r)

Results in:

Success: no issues found in 1 source file

Why does mypy yield an error when using a list (or typing.List) in this case?

0

There are 0 best solutions below