Python: Decorators Part II
In this post, we will talk about the standard python library decorators and one or more things about the decorators . If you haven't read the previous blog post about decorator, go check out that here. I will be waiting...
We will talk about functools.lru_cache Decorator from Python standard Library, where lru means Least Recently Used.
lru_cache as the name suggested, it saves the previous result of the function expression based on argument and uses that result if the same argument passed. To save expensive calculations.
maxsize means that numbers of cache result which can be cached, once the cache is full the older result is discarded. One should use maxsize value as a power of 2 for optimal performance.
type true means argument will be treated differently as int and float values as 1 and 1.0 are treated the same, but if type value is set to true it will be treated differently.
>> 1 == 1.0 >> True
lru_cache use dict to the save the argument as position and keyword-based so all the argument passed to the decorator should be hash-able.
Some point as notes to remember about the decorators
- Decorators are executed when the module is loaded by Python and decorated function only executed if explicitly invoked.
- Decorators have the power to return the entirely a different function.
- We can also have a parameterized decorator as we have seen in the lru_cache decorator.
- Stocked Decorators means when more then one decorator is applied to a function, then the order of execution, is from the decorator nearest to the function definition to outside. Let seen an example
@d2 @d1 def func: print('f') func = d2(d1(func))
so that wrap from my side on the topic Decorators.