CKTIS / Python
functools.cache
Memorizza risultati senza limiti come lru_cache(maxsize=None).
Versione: Python 3.14; repository image, production runtime not attested
Sintassi
@functools.cacheMemorizza risultati senza limiti come lru_cache(maxsize=None).
In CPython f(1) e f(1.0) creano due chiavi anche se 1 == 1.0. La chiave della chiamata deve essere hashabile e un ordine diverso degli argomenti nominati può creare voci distinte. Argomenti e risultati restano referenziati fino alla rimozione. Due mancate corrispondenze simultanee possono ripetere il calcolo.
Due square(4) danno 16 e calls contiene un solo 4.
from functools import cache
@cache
def f(x):
return object()
a = f(4)
assert f(4) is a and f.cache_info().hits == 1
f.cache_clear()
assert f(4) is not a
try:
f([])
except TypeError:
pass
else:
raise AssertionError
f.cache_clear()
assert f(1) is not f(1.0) and f.cache_info().misses == 2
Esempi
import functools
calls = []
@functools.cache
def square(n):
calls.append(n)
return n * n
print(square(4), square(4), calls)
Risultato
16 16 [4]
Due square(4) danno 16 e calls contiene un solo 4.