python / python/mypy

False negative: covariant `TypeVar`s not rejected in function signatures

Open
#12,842 1 comment 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

To Reproduce

mypy accepts the following code without issues:

from typing import Generic, TypeVar

T_co = TypeVar("T_co", covariant=True)

class FooGeneric(Generic[T_co]):
    pass

def accepts_foo(x: FooGeneric[T_co]) -> None:
    pass

Expected Behavior

My understanding is that covariant and contravariant are only allowed on type variables used to parameterise generics.

As such anything other than accepts_foo(x: FooGeneric[T]) (or accepts_foo(x: FooGeneric)) should be rejected. For example accepts_foo(x: FooGeneric[T_contra]) is also accepted, but this makes no sense: accepts_foo cannot define its own version of FooGeneric that acts contravariantly in its type variable.

Your Environment

  • Mypy version used: 0.950
  • Python version used: 3.10.0
  • Operating system and version: Ubuntu 20.04.2 on WSL2 on Windows 10

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

No source file or test is named. Start by reproducing the provided snippet with mypy and then trace the type-variable variance validation; done means signatures using covariant or contravariant TypeVars are rejected while the stated valid forms remain accepted.

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.