Two tools for caching methods are functools.cached_property() and functools.lru_cache(). Both modules are part of the functools module. The functools module is for higher-order functions: functions that act on or return other functions. Let's first install and import the functools module -
To install the functools module, use pip −
pip install functools
To import functools −
import functools
Let us understand cache one by one -
Useful for expensive computed properties of instances that are otherwise effectively immutable.
The cached_property method is only available without any parameters. It does not create a reference to the instance. Cached method results are only retained while the instance is active.
The advantage of this is that when the instance is no longer used, the cached method results will be released immediately. The disadvantage is that if the instance accumulates, the accumulated method results also accumulate. They can grow without limit.
The Chinese translation ofLet’s see an example -
class DataSet: def __init__(self, sequence_of_numbers): self._data = tuple(sequence_of_numbers) @cached_property def stdev(self): return statistics.stdev(self._data)
lru_cache method is suitable for methods with hashable parameters. Unless special effort is made to pass a weak reference, it creates a reference to the instance.
The advantage of the least recently used algorithm is that the cache is limited to a specified maximum size. The disadvantage is that instances remain active until they expire from the cache or the cache is cleared.
The Chinese translation ofLet’s see an example -
@lru_cache def count_vowels(sentence): return sum(sentence.count(vowel) for vowel in 'AEIOUaeiou')
Example of using cache to calculate Fibonacci numbers −
from functools import lru_cache @lru_cache(maxsize=None) def fib(n): if n < 2: return n return fib(n-1) + fib(n-2) print([fib(n) for n in range(16)]) print(fib.cache_info())
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610] CacheInfo(hits=28, misses=16, maxsize=None, currsize=16)
Now, let’s look at the complete example of functool cached_property() and lru_cache -
from functools import lru_cache from functools import cached_property class Weather: "Lookup weather information on a government website" def __init__(self, station_id): self._station_id = station_id # The _station_id is private and immutable def current_temperature(self): "Latest hourly observation" # Do not cache this because old results # can be out of date. @cached_property def location(self): "Return the longitude/latitude coordinates of the station" # Result only depends on the station_id @lru_cache(maxsize=20) def historic_rainfall(self, date, units='mm'): "Rainfall on a given date" # Depends on the station_id, date, and units.
The above is the detailed content of How to cache method calls in Python?. For more information, please follow other related articles on the PHP Chinese website!