False negative: isinstance() guard removes parameterisation by `TypeVar`
Open
Nobody has claimed this yet.
bug
topic-type-narrowing
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
To Reproduce
mypy does not reject the following:
from collections.abc import Mapping
from typing import TypeVar
T = TypeVar("T")
S = TypeVar("S")
def swap(x: Mapping[T, S]) -> Mapping[S, T]:
if isinstance(x, dict):
return x
else:
raise Exception
Expected Behavior
After the type guard, reveal_type indicates that x has type dict[Any, Any]. As we're already in swap then it should actually have type dict[T, S].
As a result, no error is raised despite the above code being wrong.
Your Environment
- Mypy version used: 0.95.0
- Python version used: 3.10.0
- Operating system and version: Ubuntu 20.04 on WSL2 on Windows 10
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 running the reported swap example and inspect the isinstance(x, dict) guard and its reveal_type result. Trace how mypy narrows the TypeVar-parameterized Mapping, then verify that the narrowed type retains T and S and that the incorrect return is rejected.
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
- Clearly specified
- Newbie friendliness
- 35/100