python / python/mypy

Comparison operators emit "Unsupported operand types" when using `isinstance` to narrow `TypeVar` to union of numeric types

Open
#19,454 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Bug Report

I have a generic class that wraps a bool, float, int, or str. It implements the comparison operator magic methods like __lt__ etc., using isinstance to ensure that callers don't mix bool/float/int with str. With mypy 1.16.1, this does not error, but with mypy 1.17.0, the comparison operators started emitting "error: Unsupported operand types for < (likely involving Union) [operator]"

To Reproduce

Minimal reproduction (using a generic function instead of a generic class): https://mypy-play.net/?mypy=latest&python=3.12&gist=dd4696c3ba71103c49d7a4aaf34b2aef

def f[T: float | int | str](x: T, y: T) -> bool:
    if isinstance(x, (float, int)) and isinstance(y, (float, int)):
        return x < y
    elif isinstance(x, str) and isinstance(y, str):
        return x < y
    else:
        raise TypeError

Expected Behavior

No errors.

Actual Behavior

test3.py:3: error: Unsupported operand types for < (likely involving Union)  [operator]
Found 1 error in 1 file (checked 1 source file)

It does not error if I remove the type variable and use union types directly:
def f(x: float | int | str, y: float | int | str) -> bool:

Your Environment

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

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the mypy-play reproduction and the equivalent test3.py snippet under mypy 1.17.0, then compare its TypeVar narrowing with the direct-union version. Trace the type-checking path for isinstance narrowing and comparison operators. Done means the generic example produces no error while mixed-type comparisons remain rejected.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
48/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.