Skip to content

False negative when a class-scoped covariant or contravariant TypeVar used in invariant base class #3981

@erictraut

Description

@erictraut

The following code demonstrates a hole in type checking:

from typing import TypeVar

T = TypeVar("T", covariant=True)

class MyList(list[T]): pass

def append_float(y: MyList[float]):
    y.append(1.0)

x: MyList[int] = MyList([1, 2, 3])
append_float(x)

The problem here is that T is covariant, but it's being used in a base class list whose corresponding type parameter is invariant. This means usage of the resulting subclass MyList can now violate the variance of its base class.

A type checker should catch this case and report an error.

This was discovered in this typeshed issue.

Metadata

Metadata

Assignees

No one assigned

    Labels

    addressed in next versionIssue is fixed and will appear in next published versionbugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions