Skip to content

TypeIs with isinstance fails to narrow #21508

@MarcoGorelli

Description

@MarcoGorelli

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrong
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions