Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Type narrowing with TypeGuards on unions does not work for else branches #18766

Description

@timhoffm

Bug Report

Example

from typing import TypeGuard, reveal_type


def is_int(obj: int | str) -> TypeGuard[int]:
    return isinstance(obj, int)


def whats_this(obj: int | str) -> None:
    if is_int(obj):
        reveal_type(obj)
    else:
        reveal_type(obj)


whats_this(1)       # Revealed type is "builtins.int"
whats_this("test")  # Revealed type is "Union[builtins.int, builtins.str]"

Expected Behavior

whats_this("test") should reveal "builtins.str".

Note: This already works correctly for type narrowing expressions, i.e. when changing if is_int(obj) to if isinstance(obj, int).

Actual Behavior

The type in the else branch is not narrowed.

Your Environment

  • Mypy version used: 1.15.0
  • Python version used: 3.12

Activity

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 wrong

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions