There's more...

This approach only works if the method is called without arguments, such that the result will always be the same, but what if the input varies? Since Python 3.2, there is a decorator we can use to provide basic Least Recently Used (LRU) caching of method calls based on a hash of the arguments (at least those that are hashable).

For example, let's look at a contrived and trivial example with a function that takes in two values and returns the result of some expensive logic:

def busy_bee(a, b):
# expensive logic
return result

If we had such a function, and wanted to provide a cache to store the result of commonly used input variations, we could do so easily with the lru_cache decorator from the functools package, as follows:

from functools import lru_cache

@lru_cache(maxsize=100, typed=True)
def busy_bee(a, b):
# ...

Now, we have provided a caching mechanism that will store up to 100 results under keys hashed from the input. The typed option was added in Python 3.3 and, by specifying True, we have made it so that a call having a=1 and b=2.0 will be stored separately from one with a=1.0 and b=2. Depending on how the logic operates and what the return value is, such variation may or may not be appropriate.

Learn more about the lru_cache decorator in the functools documentation at https://docs.python.org/3/library/functools.html#functools.lru_cache.

We could use this decorator for the examples earlier in this recipe to simplify the code, though we would probably use maxsize of 1 since there are no input variations to deal with, as in the following:

# viral_videos/models.py
from functools import lru_cache

# ... other imports ...


class ViralVideo(CreationModificationDateMixin, UrlMixin):
# ...
@lru_cache(maxsize=1)
def get_thumbnail_url(self):
# ...
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.134.77.195