Skip to content

Generic type incorrectly un-narrowed following TypeIs #19282

Closed

Description

@hauntsaninja
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]

Activity

  1. sterliakov commented on Jun 12, 2025

    @sterliakov
    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.

  2. brianschubert commented on Jun 12, 2025

    @brianschubert
    Collaborator

    Is this the same as #18009?

  3. brianschubert commented on Jun 12, 2025

    @brianschubert
    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]"
  4. added a commit that references this issue on Jun 21, 2025
    6886b7a
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrongtopic-type-narrowingConditional type narrowing / bindertopic-typeguard-typeisTypeGuard / TypeIs / PEP 647 / PEP 742

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions