Skip to content

TypeIs and TypeGuard fail to narrow type[C] #21677

Description

@ygale

Bug Report

A TypeIs/TypeGuard function fails to narrow a type[A] expression. A plain if guard block treats the branch as unreachable instead. A comprehension filter keeps the unnarrowed type instead.

To Reproduce

from typing_extensions import TypeIs

class A: ...
class M: ...
class B(A): ...
class C(M, A): ...

def is_m(t: type) -> TypeIs[type[M]]:
    return issubclass(t, M)

cls: type[A] = C
if is_m(cls):
    reveal_type(cls)

Expected Behavior

reveal_type(cls) reports type[<subclass of "A" and "M">].

Actual Behavior

Success: no issues found in 1 source file

No reveal_type note at all -- the branch is silently treated as unreachable.

Second repro (comprehension)

from typing import Type
from typing_extensions import TypeIs

class A: ...
class M: ...
class B(A): ...
class C(M, A): ...

def is_m(t: type) -> TypeIs[Type[M]]:
    return issubclass(t, M)

alist: list[Type[A]] = [B, C]
mlist: list[Type[M]] = [cls for cls in alist if is_m(cls)]
reveal_type(mlist)

Expected Behavior

No error, mlist is list[type[M]].

Actual Behavior

error: List comprehension has incompatible type List[type[A]]; expected List[type[M]]  [misc]

Environment

  • Mypy version used: mypy 2.2.0+dev (main branch)
  • Mypy command-line flags: none
  • Mypy configuration options from mypy.ini (and other config files): nothing special
  • Python version used: 3.12

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrong

    Fields

    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