python / python/typeshed

`functools.lru_cache` wrapped function with TypeVar has wrong return type.

Aperta
#6,987 0 commenti 0 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

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

Descrizione

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

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

Riproduci il problema con l’esempio minimo fornito usando mypy 0.931, quindi esamina le definizioni di typeshed per functools.lru_cache e functools.cache. Il lavoro è completato quando la funzione generica memorizzata nella cache rivela list[str] invece di un TypeVar non risolto, mentre l’esempio esplicito con str continua a funzionare.

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

Valutazione

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

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.