×

python · level 3 · unit 4 · lesson 4

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

A remembers answers so you never work them out twice.

Some functions get asked the same question again and again. A cache stores each answer the first time, then hands it straight back on every repeat, in one step.

Put from functools above a function and Python builds the cache for you. cache_info() shows the hits, answers found in the cache, and the misses, answers it had to work out.

Only cache a : one whose answer depends only on its arguments. Caching a function that reads the clock or a file would hand back stale answers.

from functools import lru_cache

@lru_cache
def delivery_cost(area):
    print(f"working out {area}...")
    return len(area) * 150

for area in ["LS", "M", "LS", "LS", "M"]:
    print(area, delivery_cost(area))
print(delivery_cost.cache_info())

LRU stands for least recently used: when the cache is full, the answer unused for longest is thrown away.