Skip to content

Type of literal narrowed when asserting equality to a NewType #20733

@p-sawicki

Description

@p-sawicki

Bug Report

When asserting equality between a new type and literal values, the type of the literal appears to be narrowed to the new type. This makes mypy report errors on subsequent comparisons against other new types with --strict.

This behavior starts from ad30be8. cc @hauntsaninja

To Reproduce

from typing import NewType

TEST = 1
MyInt1 = NewType("MyInt1", int)
MyInt2 = NewType("MyInt2", int)

def f(i: MyInt1, j: MyInt2) -> None:
    assert i == TEST
    if j == TEST:
        print("test")

Expected Behavior

No errors

Actual Behavior

error: Non-overlapping equality check (left operand type: "MyInt2", right operand type: "MyInt1")  [comparison-overlap]

Your Environment

  • Mypy version used: mypy 1.20.0+dev.ad30be89f146adaae398bd854146952158a53cad and up
  • Mypy command-line flags: mypy ~/test.py --strict
  • Mypy configuration options from mypy.ini (and other config files): None
  • Python version used: 3.13.5

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrongtopic-type-narrowingConditional type narrowing / binder

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions