Memoization (lru_cache)

say it: “mem-oh-ih-ZAY-shun” /ˌmɛmoʊɪˈzeɪʃən/ or “EL-AR-YOO KASH” /ˌɛl ɑr ˈju ˈkæʃ/

Saving a function's answers so repeat calls return instantly.

What is memoization?

Memoization means saving a function's answers so a repeat call with the same arguments returns instantly instead of doing the work again. @lru_cache does it for you.

from functools import lru_cache

@lru_cache
def shipping_quote(zip_code):
    print("Asking the carrier...")   # slow, so only once per zip
    return 7.5

shipping_quote("80202")
shipping_quote("80202")   # instant, no second request

Level: Freelancer · More Python terms at this level

Updated