Cached properties

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 ...

Get Django Design Patterns and Best Practices - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.