python / python/mypy

Generic[T_co] erroring when T_co = TypeVar("T_co", A, B, covariant=True) and passed subclass of A

Open
#8,806 9 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

feature topic-error-reporting topic-usability
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

I am reporting what I believe is a bug in mypy's interpretation of TypeVar when passed two constraining types and also covariant=True.

I think the below code sample is valid (per Liskov Substitution Principle), and is erroneously being reported as a type error by mypy. Here is my working example:

from typing import TypeVar, Generic, Union

class A:
    pass

class ASub(A):
    pass

class B:
    pass

# Case 1... Success: no issues found
# T_co = TypeVar("T_co", covariant=True)

# Case 2... error: Value of type variable "T_co" of "SomeGeneric" cannot be "ASub"  [type-var]
T_co = TypeVar("T_co", A, B, covariant=True)

# Case 3... Success: no issues found
# T_co = TypeVar("T_co", bound=Union[A, B], covariant=True)


class SomeGeneric(Generic[T_co]):
    pass

class SomeGenericASub(SomeGeneric[ASub]):
    pass


Potentially Related Issue

I may be re-asking the contents of https://github.com/python/mypy/issues/8611, but to be honest, I get confused by the core of the issue

non-empty covariant generic subclass of a contravariant base


Versions

python==3.6.5
mypy==0.770

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 reproducing the reported Case 2 with Python 3.6.5 and mypy 0.770, then compare its constrained TypeVar behavior with the unconstrained and bound examples. Read the potentially related discussion in issue #8611; done when the intended behavior for SomeGeneric[ASub] is established and the erroneous diagnostic is resolved or explained.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
compilers
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.