Incorrect type inference when using generics of "union" TypeVars
Nobody has claimed this yet.
- 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
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 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