Function returns the value of the cache is optimized as a function of common means. We can function, input parameters, return values are all saved, the next time this function is called with the same parameters, the results are stored directly as a return (do not need to be recalculated).
Python 3.2 and later
Let's implement a Fibonacci calculator, and use lru_cache.
from functools Import lru_cache @lru_cache (MAXSIZE = 32 ) DEF FIB (n-): IF n-<2 : return n- return FIB (. 1-n-) + FIB (2-n- ) >>> Print ([FIB (n-) for n- in Range (10 )]) # the Output: [0,. 1,. 1, 2,. 3,. 5,. 8, 13 is, 21 is, 34 is] # we can easily empty the cache for the return value, by: fib.cache_clear ( ) that maxsize parameter tells lru_cache, caching the most recent number of the return value.
functools provides lru_cache , if the cache data exceeds the parameter
maxsize
value, it (LRU) Clear least recently used cached results with LRU
The cachetools module provides more cache invalidation strategies:
- LFUCache(Least Frequently Used (LFU) cache implementation.)
- LRUCache(Least Recently Used (LRU) cache implementation.)
- RRCache(Random Replacement (RR) cache implementation.)
- TTLCache(LRU Cache implementation with per-item time-to-live (TTL) value.)
Python 2 series version
You can create any kind of caching mechanism, there are several ways to achieve the same effect, it all depends on your needs.
Here is a general cache:
from functools import wraps def memorize(function): memo = {} @wraps(function) def wrapper(*args): if args in memo: return memo[args] else: rv = function(*args) memo[args] = rv return rv return wrapper @memorize def fibonacci(n): if n < 2: return n return fibonacci(n - 1) + fibonacci(n - 2) fibonacci(25)
Caching function is achieved by the closure of example, a function is added for each cache decorators, the runtime will be created a different example of closure.
Cache parameters closure by key hash table (dict) instance to save the introduced.
Cache the return value is stored by the dictionary form, the key is a function of the parameter, the value of the function return value.