python / python/mypy

Invalid infer generic type for contravariant TypeVar inside function call

Open
#6,482 5 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug false-positive priority-1-normal topic-type-variables
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

from typing import Generic, TypeVar


T_contra = TypeVar('T_contra', contravariant=True)


class Animal:
    pass


class Cat(Animal):
    pass


class AnimalBox(Generic[T_contra]):
    def __init__(self, animal: T_contra):
        pass


def print_box(a: AnimalBox[Cat]):
    pass


animal = Animal()

print_box(AnimalBox(animal))  # error: Argument 1 to "AnimalBox" has incompatible type "Animal"; expected "Cat"

box = AnimalBox(animal)
print_box(box)  # OK

Reproduces only on contravariants. Covariants seems to be OK.
Tested on: mypy-0.680+dev.69eaf88a0b03e9f491cc22534c2d30f1d21832b2

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 Python reproduction from the issue and compare the direct constructor call with the intermediate AnimalBox assignment. Investigate generic type inference for contravariant TypeVars during function calls. Done means the direct print_box(AnimalBox(animal)) case is accepted consistently with the intermediate assignment, with a regression test covering the behavior.

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.