Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

LRU - Least recently used cache

  • Here we called (1, 2) after (1, 4) when it was still in the cache
  • When we called (1, 5) it removed the LRU pair, but it was NOT the (1, 2) pair
  • So it was in the cache even after the (1, 5) call.
import functools

@functools.lru_cache(maxsize=3)
def compute(x, y):
    print(f"Called with {x} and {y}")
    # some long computation here
    return x+y

if __name__ == "__main__":
    compute(1, 2) # Called with 1 and 2
    compute(1, 2)
    compute(1, 2)

    compute(1, 3) # Called with 1 and 3
    compute(1, 3)

    compute(1, 4) # Called with 1 and 4
    compute(1, 4)

    compute(1, 2)
    compute(1, 5) # Called with 1 and 5
    compute(1, 2)

from lru_cache_example_1 import compute

def test_compute(check_out):
    compute.cache_clear()

    compute(1, 2)
    check_out("Called with 1 and 2\n")
    compute(1, 2)
    check_out("")
    compute(1, 2)
    check_out("")

    compute(1, 3)
    check_out("Called with 1 and 3\n")
    compute(1, 3)
    check_out("")

    compute(1, 4)
    check_out("Called with 1 and 4\n")
    compute(1, 4)
    check_out("")

    compute(1, 2)
    check_out("")

    compute(1, 5)
    check_out("Called with 1 and 5\n")

    # This is now in the cache
    compute(1, 2)
    check_out("")

    # This is called again as the last addition pushed this out from the cache
    compute(1, 3)
    check_out("Called with 1 and 3\n")

    assert compute.cache_info().hits == 6
    assert compute.cache_info().misses == 5
    assert compute.cache_info().maxsize == 3
    assert compute.cache_info().currsize == 3