`functools.lru_cache` wrapped function with TypeVar has wrong return type.
Personne n'a encore pris cette issue.
- Langage dominant
- Python
- Étoiles
- 5.1k
- Forks
- 2.1k
- Merge moyen
- 1 j 19 h
- PR mergées (30 j)
- 82
Description
Hi,
I think there is a problem when using functools.lru_cache (and functools.cache). When the decorated function uses a TypeVar for typing arguments and return type, the wrapped function returend by functools.lru_cache has wrong (or unresolved) types.
This is not the case when replacing the TypeVar with an explicit type. See the mwe below. Thx.
import functools
from typing import TypeVar
_T = TypeVar("_T")
def my_func(elem: _T) -> list[_T]:
return [elem]
my_func_cached = functools.lru_cache(my_func)
a = my_func("a")
reveal_type(a) # Revealed type is "builtins.list[builtins.str*]"
a_c = my_func_cached("a")
# ERROR: this should be "builtins.list*[builtins.str]"
reveal_type(a_c) # Revealed type is "builtins.list*[_T`-1]"
# this works
def my_func_str(elem: str) -> list[str]:
return [elem]
my_func_str_cached = functools.lru_cache(my_func_str)
a_str = my_func_str("a")
reveal_type(a_str) # Revealed type is "builtins.list[builtins.str]"
a_str_c = my_func_str_cached("a")
reveal_type(a_str_c) # Revealed type is "builtins.list*[builtins.str]"
Running:
Python 3.10.1
mypy 0.931
Linux 5.16.0-arch1-1
Guide de contribution
Ouvrir le guide de contribution
Par où commencer
- Lisez l'issue en entier, puis le guide de contribution du projet.
- Signalez en commentaire que vous la prenez — cela évite que deux personnes fassent le même travail.
- Forkez le dépôt et travaillez sur une branche.
- Ouvrez une pull request qui référence le numéro de l'issue.
Piste de recherche
Reproduisez le problème avec l’exemple minimal fourni en utilisant mypy 0.931, puis examinez les définitions de typeshed pour functools.lru_cache et functools.cache. Le travail est terminé lorsque la fonction générique mise en cache révèle list[str] plutôt qu’un TypeVar non résolu, tandis que l’exemple explicite avec str continue de fonctionner.
Rédigé par le modèle d'indexation à partir du texte de l'issue.
Évaluation
- Stack technique
- python
- Domaine
- tooling
- Type d'issue
- Bug
- Difficulté
- 3/5
- Temps estimé
- 1-2 jours
- Activité
- À l'abandon
- Clarté
- Plutôt claire
- Accessibilité débutants
- 35/100