cachetools: Subclassing TTLCache[KT, VT] loses generic type inference on instantiation
Nadie ha tomado este issue todavía.
- Lenguaje dominante
- Python
- Estrellas
- 5.1k
- Forks
- 2.1k
- Merge medio
- 1 d 19 h
- PR fusionados (30 d)
- 82
Descripción
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
Guía de contribución
Primeros pasos
- Lee el issue completo y luego la guía de contribución del proyecto.
- Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
- Haz un fork del repositorio y trabaja en una rama.
- Abre un pull request que haga referencia al número del issue.
Línea de trabajo
Empieza localizando el stub de typeshed para TTLCache.init y cualquier prueba relacionada del comprobador de tipos; inspecciona cómo contribuye el argumento timer a la inferencia genérica. Reproduce el ejemplo de la subclase con mypy y Pyright y, después, verifica que la instanciación de _TrackedTTLCache(maxsize=128, ttl=600) se infiere como _TrackedTTLCache[str, int] sin la solución alternativa con cast.
Escrito por el modelo de indexación a partir del texto del issue.
Evaluación
- Stack tecnológico
- python
- Área
- developer-experience
- Tipo de issue
- Error
- Dificultad
- 3/5
- Tiempo estimado
- 1-2 días
- Estado de actividad
- Tranquilo
- Claridad
- Bastante claro
- Aptitud para principiantes
- 52/100