False positive error "incompatible type" on bound TypeVar
Open
Nobody has claimed this yet.
bug
topic-inheritance
topic-type-variables
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
Originally posted on gitter july 29th, where it was suggested I open a bug report
Bug Report
For this code:
from typing import Generic, TypeVar, Union
ListT = TypeVar("ListT", str, float)
class TestListA(Generic[ListT]):
def __init__(self, device: ListT) -> None:
self._device: ListT = device
class TestListB(TestListA[ListT]):
def __init__(self, device: ListT) -> None:
super().__init__(device)
mypy outputs error:
test.py:13: error: Argument 1 to "__init__" of "TestListA" has incompatible type "str"; expected "ListT" [arg-type]
test.py:13: error: Argument 1 to "__init__" of "TestListA" has incompatible type "float"; expected "ListT" [arg-type]
which is false positive.
Please note that when using a TypeVar with bound=Union, then mypy doesn't complain.
ListT = TypeVar("ListT", bound=Union[str, float])
Your Environment
- Mypy version used:
mypy 0.971 (compiled: yes) - Mypy command-line flags:
- Mypy configuration options from
mypy.ini(and other config files): - Python version used:
Python 3.9.12 - Operating system and version:
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 reproducing the provided TestVar example with mypy 0.971, then compare its constrained TypeVar behavior with the bound=Union variant. Locate the type-checking path for TestListB.init and add regression coverage for the false-positive diagnostics. Done means the constrained example passes without errors while incompatible calls remain diagnosed.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- compilers, devtools
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 38/100