Skip to content

[PEP 695] Incorrect Variance Computation with Polymorphic Constructor. #19439

@randolf-scholz

Description

@randolf-scholz

Bug Report

In the example below, all 3 classes should be covariant in their generic type. However, mypy seems to infer that only Bar and Baz are covariant, but not Foo. Code sample in pyright playground, mypy playground

from collections.abc import Sequence
from typing import Generic, TypeVar

class Foo[T](Sequence[T]):
    @classmethod
    def new[T2](cls: "type[Foo[T2]]", arg: list[T2]) -> "Foo[T2]": ...

class Bar[T](Sequence[T]):
    @classmethod
    def new[T2](cls, arg: list[T2]) -> "Bar[T2]": ...

_T_co = TypeVar("_T_co", covariant=True)
_S = TypeVar("_S")
class Baz(Sequence[_T_co], Generic[_T_co]):
    @classmethod
    def new(cls: "type[Baz[_S]]", arg: list[_S]) -> "Baz[_S]": ...

def test_foo_covariant(x: Foo[int]) -> Foo[object]:
    return x  # ❌ got "Foo[int]", expected "Foo[object]"
    
def test_bar_covariant(x: Bar[int]) -> Bar[object]:
    return x
    
def test_baz_covariant(x: Baz[int]) -> Baz[object]:
    return x

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions