no error on `TypeVar` with explicitly declared variance when the generic is used in another type with a different variance
Open
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)
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
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- 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