python / python/mypy

Incorrect type inference when using generics of "union" TypeVars

Open
#7,913 6 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

bug false-positive priority-1-normal topic-type-variables
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

from typing import MutableSet, Sequence, TypeVar

T = TypeVar('T', str, Sequence[str])

class CustomSet(MutableSet[T]):
    def add(self, value: T) -> None:
        pass

foo = CustomSet()
foo.add(('a', 'b'))

mypy 0.740 says: error: Argument 1 to "add" of "CustomSet" has incompatible type "Tuple[str, str]"; expected "str"

There's seemingly nothing I can do to get mypy to handle this pattern correctly. If I try explicitly specifying the type of foo, it just complains that the assignment to it is incompatible.

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 with the minimal CustomSet and TypeVar reproduction in the issue, then trace mypy's generic type inference for the call to CustomSet.add. Confirm the behavior with a focused type-checking test based on the example; done means the tuple argument is inferred and accepted without an incompatible explicit annotation.

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.