Baza wiedzyCentrum egzaminacyjne
PLPolski
Wybierz język13

CKTIS / Python

functools.cache

Zapamiętuje wyniki bez limitu jak lru_cache(maxsize=None).

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

Składnia

@functools.cache

Zapamiętuje wyniki bez limitu jak lru_cache(maxsize=None).

W CPython wywołania f(1) i f(1.0) tworzą dwa klucze, mimo że 1 == 1.0. Klucz wywołania musi być haszowalny, a różna kolejność argumentów nazwanych może tworzyć osobne wpisy. Argumenty i wyniki pozostają w pamięci do usunięcia wpisów. Równoczesne chybienia mogą powtórzyć obliczenie.

Dwa square(4) dają 16, lecz calls zawiera jedną 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

Przykłady

import functools
calls = []
@functools.cache
def square(n):
    calls.append(n)
    return n * n

print(square(4), square(4), calls)

Wynik

16 16 [4]

Dwa square(4) dają 16, lecz calls zawiera jedną 4.

Źródła