python · level 3 · unit 4 · lesson 4
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
Watch the thinking lines. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
from functools import lru_cache
@lru_cache
def slow_square(n):
print("thinking about", n)
return n * n
total = slow_square(4) + slow_square(4) + slow_square(5)
print(total)
print(slow_square.cache_info().hits)
your turn
Your turn. Cache a pretend price lookup.
Fill the blank so price_of remembers its answers. Each item should be looked up only once.
fix it
The pens sold out, but the shop still says yes.
- The second answer is out of date. Where does it come from?
- The cache hands back the old answer, because
in_stockdepends onstock, not only on its argument. - This function is not pure, so delete the
@lru_cacheline, then run.
nailed it
you taught a function to remember. :D
- A cache stores answers so repeats cost one step.
@lru_cacheadds a cache.cache_info()shows hits and misses.- Only cache pure functions, or answers go stale.
new words in your collection
- cache
- lru_cache
- pure function
This lesson isn’t saved. A free account remembers every lesson you finish.