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





































