python / python/typeshed

cachetools: Subclassing TTLCache[KT, VT] loses generic type inference on instantiation

Đang mở
#15,798 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.

stubs: false positive
Ngôn ngữ chính
Python
Star
5.1k
Fork
2.1k
Merge trung bình
1 ngày 19 giờ
Pull request đã merge (30 ngày)
82

Mô tả

Description

When subclassing TTLCache[KT, VT] with explicit generic parameters,
type checkers (tested with Pyright and mypy) fail to infer the correct
type on instantiation, reporting _SubClass[Any, Any, float] instead
of _SubClass[KT, VT].

Reproduction

from typing import Any
from cachetools import TTLCache

class _TrackedTTLCache[KT, VT](TTLCache[KT, VT]):
    def popitem(self) -> tuple[KT, VT]:
        key, value = super().popitem()
        return key, value

cache: _TrackedTTLCache[str, int] = _TrackedTTLCache(maxsize=128, ttl=600)
#     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
# Error: Expected type '_TrackedTTLCache[str, int]',
#        got '_TrackedTTLCache[Any, Any, float]' instead

Expected behavior

_TrackedTTLCache(maxsize=128, ttl=600) should be inferred as
_TrackedTTLCache[str, int] — consistent with how the explicit
annotation on the left-hand side is declared.

Root cause

The stub signature for TTLCache.__init__ likely includes float
as a third implicit type parameter (from the timer argument),
which leaks into subclass inference and overrides the declared
generic parameters.

Workaround

from typing import cast

cache = cast(
    "_TrackedTTLCache[str, int]",
    _TrackedTTLCache(maxsize=128, ttl=600),
)

Environment

  • cachetools version: 7.1.1
  • PyCharm linter
  • Python: 3.12

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ìm stub của typeshed cho TTLCache.init và mọi bài kiểm tra liên quan của trình kiểm tra kiểu; kiểm tra cách đối số timer đóng góp vào việc suy luận generic. Tái hiện ví dụ lớp con bằng mypy và Pyright, sau đó xác minh rằng việc khởi tạo _TrackedTTLCache(maxsize=128, ttl=600) được suy luận là _TrackedTTLCache[str, int] mà không cần cách khắc phục bằng cast.

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
developer-experience
Loại issue
Lỗi
Độ khó
3/5
Thời gian dự kiến
1-2 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
52/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.