Skip to content

Support assertion style type guards in exhaustive branch analysis #11238

Closed

Description

@KotlinIsland
def func(a: object, b: bool) -> None:
    if b:
        assert isinstance(a, int)
    else:
        assert isinstance(a, str)

    reveal_type(a)  # note: Revealed type is "builtins.object"

a should be narrowed to int | str but it is instead not narrowed at all.

Activity

  1. hi-ogawa commented on Oct 17, 2021

    @hi-ogawa
    Contributor

    Considering the behavior of the example below, "narrowing" is happening in some sense, but possibly mypy's join type is producing join(int, str) = object.

    # test1.py
    
    class P:
        pass
    
    
    class C1(P):
        pass
    
    
    class C2(P):
        pass
    
    
    def f(a: object, b: bool) -> None:
        if b:
            assert isinstance(a, C1)
        else:
            assert isinstance(a, C2)
    
        reveal_type(a)  # note: Revealed type is "test1.P"
  2. brianschubert commented on Apr 18, 2025

    @brianschubert
    Collaborator

    This was implemented in #18538, which should release with v1.16.0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions