python / python/mypy

Missing `TypeIs` narrowing for variadic tuples

Đang mở
#17,599 2 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
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ả

I noticed this behavior when investigating a similar issue in pyright.

Mypy isn't correctly narrowing tuples in some cases.

from typing_extensions import TypeIs


def is_tuple_of_strings(v: tuple[int | str, ...]) -> TypeIs[tuple[str, ...]]:
    return all(isinstance(x, str) for x in v)


def test1(t: tuple[int]) -> None:
    if is_tuple_of_strings(t):
        reveal_type(t)  # Should be Never ✅ 
    else:
        reveal_type(t)  # Should be tuple[int] ✅ 

def test2(t: tuple[str, int]) -> None:
    if is_tuple_of_strings(t):
        reveal_type(t)  # Should be Never ✅ 
    else:
        reveal_type(t)  # Should be tuple[str, int] ✅ 

def test3(t: tuple[int | str]) -> None:
    if is_tuple_of_strings(t):
        reveal_type(t)  # Should be tuple[str] ✅ 
    else:
        reveal_type(t)  # Should be tuple[int] or tuple[int | str] ❌ (mypy: Never)

def test4(t: tuple[int | str, int | str]) -> None:
    if is_tuple_of_strings(t):
        reveal_type(t)  # Should be tuple[str, str] ✅ 
    else:
        reveal_type(t)  # Should be tuple[int | str, int | str] or tuple[int, int | str] | tuple[str, int] ❌ (mypy: Never)

def test5(t: tuple[int | str, ...]) -> None:
    if is_tuple_of_strings(t):
        reveal_type(t)  # Should be tuple[str, ...] ✅ 
    else:
        reveal_type(t)  # Should be tuple[int | str, ...] ❌ (mypy: Never)

def test6(t: tuple[str, *tuple[int | str, ...], str]) -> None:
    if is_tuple_of_strings(t):
        reveal_type(t)  # Should be tuple[str, *tuple[str, ...], str] ❌ (mypy: tuple[str, Never, str])
    else:
        reveal_type(t)  # Should be tuple[str, *tuple[int | str, ...], str] ❌ (mypy: Never)

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 tái hiện sáu ví dụ với mypy và so sánh từng kết quả reveal_type với việc thu hẹp kiểu được mong đợi trong issue. Truy vết phần triển khai thu hẹp kiểu cho TypeIs và các tuple biến thiên, sau đó thêm kiểm thử hồi quy cho những trường hợp này. Công việc được hoàn tất khi các kiểu được reveal khớp với kết quả mong đợi và không có hồi quy.

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
Đình trệ
Độ rõ ràng
Khá rõ ràng
Mức phù hợp với người mới
35/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.