Baza znanjaCentar za ispite
HRHrvatski
Odaberi jezik13

CKTIS / Python

functools.cache

Pohranjuje rezultate bez ograničenja poput lru_cache(maxsize=None).

Verzija: Python 3.14; repository image, production runtime not attested

Sintaksa

@functools.cache

Pohranjuje rezultate bez ograničenja poput lru_cache(maxsize=None).

U CPythonu f(1) i f(1.0) stvaraju dva ključa iako vrijedi 1 == 1.0. Ključ poziva mora podržavati hashiranje, a drugi poredak imenovanih argumenata može stvoriti zasebne unose. Reference na argumente i rezultate ostaju do uklanjanja. Istodobni promašaji mogu ponoviti izračun.

Dva square(4) daju 16 i calls sadrži jednu 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

Primjeri

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) daju 16 i calls sadrži jednu 4.

Izvori