python / python/mypy

Decorator with constrained TypeVar specializes to first constraint

Đang mở
#20,437 3 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-calls
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

Changing the order of constraints of TypeVar T changes whether or not mypy passes. The wrapped method always gets narrowed to whatever the first constraint type is set to.

To Reproduce

from collections.abc import Callable
from typing import TypeVar, reveal_type


T = TypeVar("T", str, bytes)  # fails
# T = TypeVar("T", bytes, str)  # passes

def decorator(fn: Callable[[T], T]) -> Callable[[T], T]:
    def wrapped(data: T) -> T:
        return fn(data)
    return wrapped

@decorator
def process(data: T) -> T:
    return data

b: bytes = b"test"
result = process(b)

Or see mypy playground: https://mypy-play.net/?mypy=latest&python=3.12&gist=12fd2e05764d26a16cd1d16a10897671

Expected Behavior

Ideally pass for both versions, or consistently fail regardless of the constraint order.
On pyright playground the revealed types match my expectations and pass with either TypeVar order

Actual Behavior

mypy passes or fails depending on TypeVar constraint order, or the data input type

Your Environment

Same behavior with all tested mypy versions (1.6.0 .. 1.19.1) and python 3.11+

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 reproducer tối thiểu cho decorator và TypeVar có ràng buộc từ issue, sau đó lần theo cách mypy xử lý việc chuyên biệt hóa các ràng buộc và callable được bọc. Hoàn tất khi kết quả không còn phụ thuộc vào thứ tự của các ràng buộc TypeVar, với coverage cho cả hai thứ tự ràng buộc.

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
42/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.