python / python/typeshed

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

オープン
#15,798 コメント 2 件 リアクション 0 件 担当者 0 名 GitHub で見る

まだ誰も着手していません。

stubs: false positive
主要言語
Python
スター
5.1k
フォーク
2.1k
平均マージ
1日 19時間
マージ済み PR(30日)
82

説明

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

コントリビューションガイド

コントリビューションガイドを開く

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

調査の方向性

まず、TTLCache.init の typeshed スタブと、関連する型チェッカーのテストを探します。timer 引数がジェネリック型の推論にどのように関与するかを調べます。次に、サブクラスの例を mypy と Pyright で再現し、_TrackedTTLCache(maxsize=128, ttl=600) のインスタンス化が cast の回避策なしで _TrackedTTLCache[str, int] と推論されることを確認します。

索引モデルが issue の本文から書いたものです。

評価

技術スタック
python
領域
developer-experience
issue の種類
バグ
難易度
3/5
見積もり時間
1〜2日
活発さ
静か
明瞭さ
おおむね明確
初心者へのやさしさ
52/100

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。