ID EN
Functools

lru_cache

Python 3.11 🇮🇩 Bahasa Indonesia

Dekorator untuk menggabungkan fungsi dengan callable memoizing yang menyimpan hingga ukuran maksimal panggilan terbaru. Ini dapat menghemat waktu ketika fungsi mahal atau fungsi terikat I/O dipanggil secara berkala dengan argumen yang sama.

Syntax

PYTHON
@functools.lru_cache(user_function)

Contoh

Example 1
PYTHON
@lru_cache
def count_vowels(sentence):
    return sum(sentence.count(vowel) for vowel in 'AEIOUaeiou')
Example 2
PYTHON
@lru_cache(maxsize=32)
def get_pep(num):
    'Retrieve text of a Python Enhancement Proposal'
    resource = 'https://peps.python.org/pep-%04d/' % num
    try:
        with urllib.request.urlopen(resource) as s:
            return s.read()
    except urllib.error.HTTPError:
        return 'Not Found'

>>> for n in 8, 290, 308, 320, 8, 218, 320, 279, 289, 320, 9991:
...     pep = get_pep(n)
...     print(n, len(pep))

>>> get_pep.cache_info()
CacheInfo(hits=3, misses=8, maxsize=32, currsize=8)
Example 3
PYTHON
@lru_cache(maxsize=None)
def fib(n):
    if n < 2:
        return n
    return fib(n-1) + fib(n-2)

>>> [fib(n) for n in range(16)]
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610]

>>> fib.cache_info()
CacheInfo(hits=28, misses=16, maxsize=None, currsize=16)

See Also

hashable dict named tuple How do I cache method calls?