python / python/mypy

[PEP 695] Incorrect Variance Computation with Polymorphic Constructor.

Open
#19,439 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug topic-pep-695 topic-type-variables
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

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

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by running the provided example in the mypy playground with the linked Python and mypy versions, then compare its behavior with the pyright playground. Investigate variance inference for the three PEP 695 class definitions and polymorphic constructors; done means mypy accepts Foo[int] where Foo[object] is expected, as it already does for Bar and Baz.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.