python / python/mypy

TypeIs and TypeGuard fail to narrow type[C]

Open
#21,677 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

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 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

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

No project file or test is named. Start by searching the type-narrowing tests and implementation for TypeIs, TypeGuard, conditional branches, and comprehension filters, then run both reproductions with mypy. Done means the first reveal_type reports the expected intersection type and the second infers list[type[M]] without an error.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
compilers, devtools
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Quiet
Clarity
Mostly clear
Newbie friendliness
55/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.