Skip to content

Generic type incorrectly un-narrowed following TypeIs #19282

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
hauntsaninja opened this issue Jun 12, 2025 · 3 comments
Open

Generic type incorrectly un-narrowed following TypeIs #19282

hauntsaninja opened this issue Jun 12, 2025 · 3 comments
Labels
bug mypy got something wrong topic-type-narrowing Conditional type narrowing / binder topic-typeguard-typeis TypeGuard / TypeIs / PEP 647 / PEP 742

Comments

@hauntsaninja
Copy link
Collaborator

from typing_extensions import Any, TypeIs, reveal_type

class C[T]:
    v: T

def is_int(v: object) -> TypeIs[C[int]]: ...

def f(c: C[Any]):
    if is_int(c):
        reveal_type(c)
    reveal_type(c)  # should be C[Any], but is C[int]
@hauntsaninja hauntsaninja added bug mypy got something wrong topic-typeguard-typeis TypeGuard / TypeIs / PEP 647 / PEP 742 labels Jun 12, 2025
@sterliakov
Copy link
Collaborator

Even worse,

from typing_extensions import Any, TypeIs, reveal_type

class C[T]:
    v: T

def is_int(v: object) -> TypeIs[C[int]]: ...

def f(c: C[Any]) -> None:
    if is_int(c):
        reveal_type(c)  # N: Revealed type is "__main__.C[builtins.int]"
    else:
        reveal_type(c)  # E: Statement is unreachable  [unreachable]
    reveal_type(c)  # N: Revealed type is "__main__.C[builtins.int]"

C[Any] can definitely be some C that is not C[int]! These two problems have the same cause - "implicit" else was unreachable, so the binder narrowed c to union of reachable branches.

@brianschubert
Copy link
Collaborator

Is this the same as #18009?

@brianschubert
Copy link
Collaborator

It seems #18193 fixes this, I'll see about picking that back up

from typing_extensions import Any, TypeIs, reveal_type

class C[T]:
    v: T

def is_int(v: object) -> TypeIs[C[int]]: ...

def f(c: C[Any]) -> None:
    if is_int(c):
        reveal_type(c)  # N: Revealed type is "__main__.C[builtins.int]"
    else:
        reveal_type(c)  # N: Revealed type is "__main__.C[Any]"
    reveal_type(c)  # N: Revealed type is "__main__.C[Any]"

@brianschubert brianschubert added the topic-type-narrowing Conditional type narrowing / binder label Jun 12, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug mypy got something wrong topic-type-narrowing Conditional type narrowing / binder topic-typeguard-typeis TypeGuard / TypeIs / PEP 647 / PEP 742
Projects
None yet
Development

No branches or pull requests

3 participants