May 2018
Beginner to intermediate
282 pages
7h 58m
English
Each time we call a property, we are recalculating a function. If it is an expensive calculation, we might want to cache the result. This way, the next time the property is accessed, the cached value is returned:
from django.utils.functional import cached_property
#...
@cached_property
def full_name(self):
# Expensive operation e.g. external service call
return "{0} {1}".format(self.firstname, self.lastname)
The cached value will be saved as a part of the Python instance in memory. As long as the instance exists, the same value will be returned.
As a fail-safe mechanism, you might want to force the execution of the Expensive operation to ensure that stale values are not returned. In such cases, set a keyword argument such ...
Read now
Unlock full access