Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between @cached_property and @lru_cache decorator

Tags:

python

django

I am new to Django. Would be really helpful if someone can tell the difference between @cached_property and @lru_cache decorator in Django. Also when should I use which decorator in Django. Use cases would be really helpful. Thanks.

like image 691
Roushan Kumar Avatar asked Mar 22 '18 19:03

Roushan Kumar


Video Answer


1 Answers

First and foremost, lru_cache is a decorator provided by the Python language itself as of version 3.4; cached_property is a decorator provided by Django for many years, while only being added to the Python language in version 3.8 in October 2019. That being said, they are similar.

lru_cache is specifically useful in functional programming. What it does is saves the results of function calls with a certain set of parameters. When a function decorated with lru_cache is called multiple times with the same parameters, the decorator will just return a cached result of the function result. This employs a method of programming called dynamic programming, and more specifically, memoization. Using these methods, you can drastically speed up code which repeatedly calls functions that are computationally expensive.

Python also provides another similar decorator called lfu_cache. Both of these decorators accomplish memoization, however with different replacement policies. lru_cache (least recently used) will fill it's cache and have to kick something out during the next decorated function call. This replacement policy dictates that the least recently used entry gets replaced by the new data. lfu_cache (least frequently used) dictates that replacements happen based on which entries are used the least.

cached_property is similar to lru_cache in the sense that it caches the result of expensive function calls. The only difference here is that it can only be used on methods, meaning the functions belong to an object. Furthermore, they can only be used on methods that have no other parameters aside from self. You would specifically want to use this during django development for a method on a class that hits the database. The Django docs mention its usage on a model class which has a property method friends. This method presumably hits the database to gather a set of people who are friends of that instance of Person. Because calls to the database are expensive, we'd want to cache that result for later use.

like image 93
Kevin Cianfarini Avatar answered Oct 24 '22 20:10

Kevin Cianfarini