From the course: Python: Decorators

Unlock the full course today

Join today to access over 22,600 courses taught by industry experts or purchase this course individually.

Use decorators as a cache

Use decorators as a cache - Python Tutorial

From the course: Python: Decorators

Start my 1-month free trial

Use decorators as a cache

- What we found when trying to calculate the values of the Fibonacci sequence using a recursive function, is that several calculations are recomputed. So how could we optimize this process? Well, one way to go about it is to store the results of each computation when they're completed so that you can use them again. This technique is known as memoization. Think of the word memorization without the letter R. Python also has a built in decorator for memorizing functions. This is LRU cache from functools. So go ahead and grab the cache.py file, and let's use LRU cache. So let's go ahead and decorate our fib function. So at LRU cache, and let's set the MAX SIZE argument to none. This indicates that there's no limit to the size of the cache. Now let's go ahead and try the Fibonacci sequence. And let's get an idea of how fast this is. So we're running this for fib 18. So this is two calculated the 18th number in the…

Contents