python / python/mypy

no error on `TypeVar` with explicitly declared variance when the generic is used in another type with a different variance

Open
#17,909 0 comments 2 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

# mypy: enable-incomplete-feature=NewGenericSyntax
# mypy: disable-error-code=empty-body

from typing import Generic, TypeVar

class Contravariant[T]:
    def fn(self, value: T) -> None:
        ...

class Foo[T]:
    def fn(self) -> Contravariant[T]: ...

def call_foo_with_string(foo: Foo[object]) -> None:
    foo.fn().fn("")

foo_number = Foo[int]()
call_foo_with_string(foo_number) # correct error: Argument 1 to "call_foo_with_string" has incompatible type "Foo[int]"; expected "Foo[object]"


out_T = TypeVar('out_T', covariant=True)
class Bar(Generic[out_T]):
    def fn(self) -> Contravariant[out_T]: ...

def call_bar_with_string(bar: Bar[object]) -> None:
    bar.fn().fn("")

bar_number = Bar[int]()
call_bar_with_string(bar_number) # no error (incorrect)

playground

in this example, the variance rules are inverted when the generic is passed to another class where it becomes contravariant (as in, the generic must now only be used in an output position)

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 reproducer with mypy and compare the NewGenericSyntax and TypeVar/Generic cases. Trace how explicitly declared variance is checked when the generic is nested in Contravariant. Done means the second call reports the same incompatibility as the first, with regression coverage for this reproducer.

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.