python / python/mypy

Plugging a contravariant Typevar into an invariant generic can make mypy miss problems

Open
#14,467 3 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

Bug Report

In the code below, plugging the contravariant TypeVar T_contra into the invariant slot in generic Data makes mypy forget about the contravariance and the error "Cannot use a contravariant type variable as return type" is not generated. The code fails at runtime.

To Reproduce

from typing import Generic, TypeVar, Type

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


class Data(Generic[T]):
    d: T


class Test(Generic[T_contra]):
    def __init__(self, some_type: Type[T_contra]) -> None:
        self._type = some_type

    def f(self) -> Data[T_contra]:
        result = Data[T_contra]()
        result.d = self._type()
        return result


t: Test[str] = Test[object](object)
assert isinstance(t.f(), str)

Expected Behavior

Report a similar error as when I try to return T_contra instead of Data[T_contra] ("Cannot use a contravariant type variable as return type")

Actual Behavior

The code passes type checking, but fails at runtime.

Your Environment

  • Mypy version used: 0.991
  • Mypy command-line flags: no extra flags
  • Mypy configuration options from mypy.ini (and other config files): no configuration file
  • Python version used: 3.8.16

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 Python reproduction with mypy and compare it with the direct contravariant-TypeVar return case described in the report. No repository file or test is named; done means adding coverage and producing a diagnostic for the Data[T_contra] return, without allowing valid invariant generic uses to regress.

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
38/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.