Skip to content

Spurious error with constrained type variables in generic functions #5493

Closed
@whoiscc

Description

@whoiscc

Reproduction:

from typing import TypeVar, List


class A:
    pass


class B(A):
    pass


class C:
    pass


LooseType = TypeVar('LooseType', A, B, C)
ListType = List[LooseType]


def foo(xs: ListType[LooseType]) -> None:
    pass


StrictType = TypeVar('StrictType', B, C)


def bar(xs: ListType[StrictType]) -> None:
    foo(xs)

This is denied with error reporting:

test.py:28: error: Argument 1 to "foo" has incompatible type "List[B]"; expected "List[A]"
test.py:28: note: "List" is invariant -- see http://mypy.readthedocs.io/en/latest/common_issues.html#variance
test.py:28: note: Consider using "Sequence" instead, which is covariant

Is this really not allowed? If B is not derived from A, then everything is ok.

In my original code, the container of A, B and C is Dict[List[Tuple[LooseType, str]]]. I cannot change List to Sequence because I need append method.

In addition, the notes disappear in complicated case.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions