CKTIS / Python
functools.cache
Shranjuje rezultate brez omejitve kot lru_cache(maxsize=None).
Različica: Python 3.14; repository image, production runtime not attested
Sintaksa
@functools.cacheShranjuje rezultate brez omejitve kot lru_cache(maxsize=None).
V CPythonu ustvarita f(1) in f(1.0) dva ključa, čeprav velja 1 == 1.0. Ključ klica mora biti zgoščljiv in drug vrstni red imenovanih argumentov lahko ustvari ločene vnose. Sklici na argumente in rezultate ostanejo do odstranitve. Hkratni zgrešitvi lahko ponovita izračun.
Dva square(4) dasta 16 in calls vsebuje eno 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
Primeri
import functools
calls = []
@functools.cache
def square(n):
calls.append(n)
return n * n
print(square(4), square(4), calls)
Rezultat
16 16 [4]
Dva square(4) dasta 16 in calls vsebuje eno 4.