`TypeIs` with `isinstance` fails to narrow
Dieses Issue hat noch niemand übernommen.
- Vorherrschende Sprache
- Python
- Sterne
- 20.6k
- Forks
- 3.3k
- PR-Merge-Kennzahlen
- PR-Kennzahlen ausstehend
Beschreibung
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
Beitragsleitfaden
Erste Schritte
- Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
- Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
- Forke das Repository und arbeite in einem Branch.
- Öffne einen Pull Request, der die Issue-Nummer nennt.
Rechercherichtung
Beginne mit dem verlinkten mypy-play-Reproducer und vergleiche den aufgedeckten Typ für den TypeIs/isinstance-Zweig mit der erwarteten Ausgabe. Verfolge die Einstiegspunkte für die Typverengung von TypeIs und isinstance und überprüfe anschließend, dass das Beispiel nur SliceStr aufdeckt, und füge eine Abdeckung für diese Regression hinzu, falls der relevante Testort gefunden wird.
Vom Indexierungsmodell aus dem Issue-Text verfasst.
Bewertung
- Tech-Stack
- python
- Bereich
- devtools
- Issue-Typ
- Bug
- Schwierigkeit
- 4/5
- Geschätzter Aufwand
- 3-5 Tage
- Aktivitätsstatus
- Ruhig
- Klarheit
- Größtenteils klar
- Anfängerfreundlichkeit
- 52/100