python / python/mypy

[2.0 regression] Bad result from heuristic non-narrowing of type[T]

Open
#21,701 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug topic-type-narrowing
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Bug Report

(A clear and concise description of what the bug is.)

To Reproduce

from math import isnan
from typing import TypeVar

V = TypeVar("V")


def assert_scalar_equal(s1: V, s2: V, /) -> None:
    assert type(s1) is type(s2)
    if type(s1) is float and type(s2) is float and isnan(s2):
        assert isnan(s1)
    else:
        assert s1 == s2

Expected Behavior

This snippet should type check.

Actual Behavior

mypy.ini: No [mypy] section in config file
t.py:9: error: Argument 1 to "isnan" has incompatible type "V"; expected "SupportsFloat | SupportsIndex"  [arg-type]
t.py:10: error: Argument 1 to "isnan" has incompatible type "V"; expected "SupportsFloat | SupportsIndex"  [arg-type]
Found 2 errors in 1 file (checked 1 source file)

Even more minimal reprod:

from math import isnan
from typing import TypeVar

V = TypeVar("V")


def foo(s1: V, /) -> None:
    if type(s1) is float:
        assert isnan(s1)
mypy.ini: No [mypy] section in config file
t.py:9: error: Argument 1 to "isnan" has incompatible type "V"; expected "SupportsFloat | SupportsIndex"  [arg-type]
Found 1 error in 1 file (checked 1 source file)

Your Environment

  • Mypy version used: 2.0.0 or 2.1.0
  • Mypy command-line flags: None
  • Mypy configuration options from mypy.ini (and other config files): None
  • Python version used: tested 3.11.14 and 3.14.6

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 by running the minimal t.py reproduction with mypy 2.0.0 or 2.1.0 and inspect the type-narrowing behavior after type(s1) is float. Compare it with the expected narrowing for isnan; done means both provided snippets type check without the reported arg-type errors.

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
Quiet
Clarity
Mostly clear
Newbie friendliness
55/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.