cachetools: Subclassing TTLCache[KT, VT] loses generic type inference on instantiation
まだ誰も着手していません。
- 主要言語
- 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
cachetoolsversion: 7.1.1- PyCharm linter
- Python: 3.12
コントリビューションガイド
はじめの一歩
- issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
- 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
- リポジトリをフォークし、ブランチを切って変更します。
- 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