flâneur — a map of the web's best reading

6 Cool Things You Can Do With The Functools Module - Pybites

pybit.es · 1,123 words · saved by 1 readers

In this article let’s look at the functools Standard Library module and 6 cool things you can do with it (be warned, a lot of decorators are coming your way! 😍) … You can use the @cache decorator (formerly called @lru_cache) as a “simple lightweight unbounded function cache”. The classic example is calculating a Fibonacci series where the intermediate results are cached, speeding up the calculation significantly: On my system this code takes 0.02s to complete. 😎 However if I comment the @cache decorator it takes 28.30s because of all the repeated calculations! 😱 Hence caching is especially useful and crucial for tasks with expensive repeat computations. New to caching? Check out our YouTube video. You can do the same for properties using @cached_property. Using the @total_ordering decorator you can write the __eq__() dunder and one of __lt__(), __le__(), __gt__(), or __ge__(), so only two, and it will provide the other ones automatically for you. Less code, nice automation. As per t

In this article let&#8217;s look at the functools Standard Library module and 6 cool things you can do with it (be warned, a lot of decorators are coming your way! 😍) &#8230; 1. Cache (&#8220;memoize&#8221;) things You can use the @cache decorator (formerly called @lru_cache ) as a &#8220;simple lightweight unbounded function cache&#8221;. The classic example is calculating a Fibonacci series where the intermediate results are cached, speeding up the calculation significantly: from functools import cache @cache def fibonacci(n: int) -> int: if n <= 1: return n return fibonacci(n - 1) + fibona

Explore this link on the map →

related reading