Skip to content

[1.18 regression] Negative type narrowing of TypeIs of Union with TypeVar not working #20330

Description

@FancyNeuron

Bug Report

When I use a TypeIs on a union of a TypeVar and something else (for example int), it seems the negative type narrowing does not work. mypy accepts it as safe in version 1.17.1, but fails since 1.18.1.
In my stack overflow question about this, a commenter said this was changed in #18193 and they suspect it to be a bug. I don't know if it is a bug, however the code below sure looks safe to me.

To Reproduce

Check the following code with mypy, at least version 1.18.1
mypy playground

from typing import TypeVar, Callable, Any
from typing_extensions import TypeIs

_T = TypeVar('_T')

def foo(x: _T | int, checker: Callable[[Any], TypeIs[_T]], default: int) -> int:
    if checker(x):
        return default
    else:
        return x

Expected Behavior
Succeeds

Actual Behavior
Fails

main.py:12: error: Incompatible return value type (got "_T | int", expected "int")  [return-value]
Found 1 error in 1 file (checked 1 source file)

-> Error is raised on the return line in the else branch

Your Environment

  • Mypy version used: 1.18.1
  • Mypy command-line flags: none
  • Mypy configuration options from mypy.ini (and other config files): unchanged
  • Python version used: 1.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 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