python / python/mypy

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

Đang mở
#21,701 1 bình luận 0 reaction 0 người được giao Xem trên GitHub

Chưa có ai nhận issue này.

bug topic-type-narrowing
Ngôn ngữ chính
Python
Star
20.6k
Fork
3.3k
Chỉ số merge pull request
Chỉ số pull request đang chờ

Mô tả

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

Hướng dẫn đóng góp

Mở hướng dẫn đóng góp

Bắt đầu từ đâu

  1. Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
  2. Bình luận trên issue rằng bạn sẽ nhận — tránh hai người làm cùng một việc.
  3. Fork repository và làm thay đổi trên một nhánh.
  4. Mở pull request có tham chiếu số hiệu của issue.

Hướng nghiên cứu

Bắt đầu bằng cách chạy bản tái hiện tối thiểu t.py với mypy 2.0.0 hoặc 2.1.0 và kiểm tra hành vi thu hẹp kiểu sau type(s1) is float. So sánh với việc thu hẹp kiểu dự kiến cho isnan; được xem là hoàn tất khi cả hai snippet được cung cấp đều kiểm tra kiểu thành công mà không có các lỗi arg-type đã báo cáo.

Do mô hình lập chỉ mục viết ra từ nội dung của issue.

Đánh giá

Công nghệ
python
Lĩnh vực
devtools
Loại issue
Lỗi
Độ khó
4/5
Thời gian dự kiến
3-5 ngày
Mức độ hoạt động
Ít trao đổi
Độ rõ ràng
Khá rõ ràng
Mức phù hợp với người mới
55/100

Nhận issue mới trong hộp thư của bạn

Bản tóm tắt ngắn những issue GitHub phù hợp với người mới.