liveBook · Manning

Caching

As explained in The Quick Python Book, Fourth Edition

A cache is stored data containing previously computed results so that later requests can reuse them without repeating the computation.

Caching stores previously computed results so repeated requests can reuse them instead of repeating expensive work. A Python dictionary makes a compact in-memory cache: use an argument combination as a tuple key, check whether it exists, and store the result after calculating it. section 7.6

A basic function cache follows this sequence:

  • Receive the function arguments and combine them into a tuple such as (m, n, t). section 7.6
  • Return the dictionary value immediately when the tuple is already present. section 7.6
  • Persist the dictionary with pickle when later program sessions should reuse the cache. section 13.8

Caching a time-consuming function

sole_cache = {} def sole(m, n, t): if (m, n, t) in sole_cache: return sole_cache[(m, n, t)] result = expensive_calculation(m, n, t) sole_cache[(m, n, t)] = result return result Calls with the same three arguments reuse the stored result. A disk-backed version loads the dictionary at startup and saves it later, allowing multiple sessions to share accumulated results.

sole_cache = {}
def sole(m, n, t):
   if (m, n, t) in sole_cache:
       return sole_cache[(m, n, t)]
   else:
       # . . . do some time-consuming calculations . . .
       sole_cache[(m, n, t)] = result
       return result

Inspect the compact dictionary implementation of a cache, including the tuple lookup, miss path, result assignment, and return. section 7.6

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Demonstrates in-memory lookup and disk persistence, but leaves concurrency handling unresolved.
Examples
Uses the sole calculation, repeated argument triples, a spreadsheet-cell exercise, and a pickled cache file.
What it assumes
Assumes dictionary operations and suitable keys, while illustrating tuple keys for combinations of function arguments.
What you can do after
Apply it via Python dictionaries and pickle to avoid repeated calculations within and across program sessions.
How it connects
Connects dictionaries, tuple keys, function arguments, pickling, and file persistence.

Also explained in

Compare how 38 books explain caching →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Quick Python Book, Fourth Edition. The section links point to the parts of the book it draws on.