`TypeIs` with `isinstance` fails to narrow
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
Bug Report
If I use TypeIs along with isinstance, the type doesn't get narrowed
To Reproduce
from typing import TypeIs, Any, TypeAlias, reveal_type
SliceInt: TypeAlias = slice[int | None, int | None, int | None]
SliceStr: TypeAlias = slice[str | None, str | None, str | None]
def is_slice_int(obj: Any) -> TypeIs[SliceInt]: # type: ignore[empty-body]
...
def main(obj: SliceInt | SliceStr) -> None:
if is_slice_int(obj):
pass
elif isinstance(obj, slice):
reveal_type(obj)
https://mypy-play.net/?mypy=latest&python=3.14&gist=170b0c83ef93742ff998485be01e9440
Expected Behavior
t.py:19: note: Revealed type is "slice[str | None, str | None, str | None]"
Actual Behavior
t.py:19: note: Revealed type is "slice[int | None, int | None, int | None] | slice[str | None, str | None, str | None]"
Note that, for comparison, pyright and pyrefly get this right:
(scratch) mgorelli@marcoslaptop:~/scratch$ pyright t.py
pyre/home/mgorelli/scratch/t.py
/home/mgorelli/scratch/t.py:19:21 - information: Type of "obj" is "slice[str | None, str | None, str | None]"
0 errors, 0 warnings, 1 information
(scratch) mgorelli@marcoslaptop:~/scratch$ pyright t.py
/home/mgorelli/scratch/t.py
/home/mgorelli/scratch/t.py:19:21 - information: Type of "obj" is "slice[str | None, str | None, str | None]"
0 errors, 0 warnings, 1 information
(scratch) mgorelli@marcoslaptop:~/scratch$ pyrefly check t.py
INFO revealed type: slice[str | None, str | None, str | None] [reveal-type]
--> t.py:19:20
|
19 | reveal_type(obj)
| -----
|
INFO 0 errors
Your Environment
- Mypy version used: 2.1.0
- Mypy command-line flags:
- Mypy configuration options from
mypy.ini(and other config files): - Python version used: 3.13.13
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 linked mypy-play reproducer and compare the revealed type for the TypeIs/isinstance branch with the expected output. Trace the type-narrowing entry points for TypeIs and isinstance, then verify that the example reveals only SliceStr and add coverage for this regression if the relevant test location is found.
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
- Quiet
- Clarity
- Mostly clear
- Newbie friendliness
- 52/100