python / python/mypy

variance inferred incorrectly when class has both a covariant and contravariant generic and instance attribute is assigned without a type annotation

Open
#18,147 0 comments 1 reaction 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

from typing import Never


class Foo[in_T, out_T]:
    def __init__(self, *, value: out_T):
        a: Foo[Never, object] = self # error (incorrect)
        self.__a = value
        reveal_type(self.__a) # out_T`2

    def asdf(self, value: in_T) -> out_T: ...


class Bar[in_T, out_T]:
    def __init__(self, *, value: out_T):
        a: Bar[Never, object] = self # no error (correct)
        self.__a: out_T = value
        reveal_type(self.__a) # out_T`2

    def asdf(self, value: in_T) -> out_T: ...

playground

(originally raised in #18118 but i messed up the minimal repro)

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 with the linked mypy-play reproduction and compare the Foo and Bar cases, focusing on variance inference when the private instance attribute lacks an annotation. Check the original context in issue #18118 if needed; done means the Foo assignment no longer reports the incorrect error while the revealed type remains correct.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
compilers, 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.