How to cache method calls in Python?

王林
Release: 2023-09-10 17:37:02
forward
641 people have browsed it

How to cache method calls in Python?

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 -

Install functools

To install the functools module, use pip −

pip install functools
Copy after login

Import function tool

To import functools −

import functools
Copy after login

Let us understand cache one by one -

cached_property()

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 of

Example

is:

Example

Let’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)
Copy after login

lru_cache

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 of

Example

is:

Example

Let’s see an example -

@lru_cache def count_vowels(sentence): return sum(sentence.count(vowel) for vowel in 'AEIOUaeiou')
Copy after login

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())
Copy after login

Output

[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)
Copy after login

Caching example

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.
Copy after login

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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!