CKTIS / Python
functools.cache
Ukladá výsledky bez obmedzenia ako lru_cache(maxsize=None).
Verzia: Python 3.14; repository image, production runtime not attested
Syntax
@functools.cacheUkladá výsledky bez obmedzenia ako lru_cache(maxsize=None).
V CPythone vytvoria f(1) a f(1.0) dva kľúče, hoci 1 == 1.0. Kľúč volania musí byť hašovateľný a iné poradie pomenovaných argumentov môže vytvoriť ďalšiu položku. Argumenty aj výsledky zostávajú odkazované do odstránenia. Súbežné nenájdenia môžu výpočet zopakovať.
Dve square(4) dajú 16 a calls obsahuje jedinú 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
Príklady
import functools
calls = []
@functools.cache
def square(n):
calls.append(n)
return n * n
print(square(4), square(4), calls)
Výsledok
16 16 [4]
Dve square(4) dajú 16 a calls obsahuje jedinú 4.