python / python/typeshed

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

Aperta
#15,798 2 commenti 0 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

stubs: false positive
Lingua principale
Python
Stelle
5.1k
Fork
2.1k
Merge medio
1g 19h
PR unite (30g)
82

Descrizione

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

Guida per i contributori

Apri la guida per i contributori

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Direzione di ricerca

Inizia individuando lo stub di typeshed per TTLCache.init e tutti i test correlati del type checker; esamina in che modo l’argomento timer contribuisce all’inferenza dei generics. Riproduci l’esempio della sottoclasse con mypy e Pyright, quindi verifica che l’istanza di _TrackedTTLCache(maxsize=128, ttl=600) venga inferita come _TrackedTTLCache[str, int] senza la soluzione alternativa con cast.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Valutazione

Stack tecnologico
python
Ambito
developer-experience
Tipo di issue
Bug
Difficoltà
3/5
Tempo stimato
1-2 giorni
Stato di attività
Tranquilla
Chiarezza
Abbastanza chiara
Idoneità per principianti
52/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.