cachetools: Subclassing TTLCache[KT, VT] loses generic type inference on instantiation
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 5.1k
- Forks
- 2.1k
- Avg merge
- 1d 19h
- Merged PRs (30d)
- 82
Description
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
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by locating the typeshed stub for TTLCache.init and any related type-checker tests; inspect how the timer argument contributes to generic inference. Reproduce the subclass example with mypy and Pyright, then verify that instantiating _TrackedTTLCache(maxsize=128, ttl=600) is inferred as _TrackedTTLCache[str, int] without the cast workaround.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- developer-experience
- Issue type
- Bug
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Quiet
- Clarity
- Mostly clear
- Newbie friendliness
- 52/100