Skip to content

[1.20 regression] Too aggressive type narrowing with type variables and equality #21199

Description

@kdarnok

Bug Report

This is about the type narrowing logic updated in 1.20.0: == and in may cause a variable to lose its type: when checked against a type var, these checks cause the lhs variable to assume the type of the rhs. In general the resulting type should probably be some kind of intersection. Without such a construct there are certainly situations where the current behavior might be expected (and it's certainly correct where the variable is of a type that's a supertype of the one checked against), but also where this will be quite confusing.

To Reproduce

fromtypingimportHashable, TypeVarH=TypeVar('H', bound=Hashable)
deffunc(y: H):
x: intassertx==yreveal_type(x) # Revealed type is "H"x+=1# Unsupported operand types for + ("H" and "int")

Playground

So, the check causes x to lose its type.

Expected Behavior

No error to be thrown.

Your Environment

  • Mypy version used: 1.20.0
  • Mypy command-line flags: none
  • Mypy configuration options from mypy.ini (and other config files): none
  • Python version used: 3.11.12

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions