python / python/mypy

False positive error "incompatible type" on bound TypeVar

Open
#13,596 1 comment 1 reaction 0 assignees View on GitHub

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

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 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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.