In this lesson, you’ll learn about the
functools module. This module contains some useful higher order functions like
reduce() and some decorators like
functools.reduce() is useful to apply a function over and over on an iterable to “reduce” it to one single value:
>>> from functools import reduce >>> reduce(lambda x, y: x * y, [1, 2, 3, 4]) 24
functools.cached_property is available in Python 3.8 and above and allows you to cache class properties. Once a property is evaluated, it won’t be evaluated again.
functools.lru_cache allows you to cache recursive function calls in a least recently used cache. This can optimize functions with multiple recursive calls like the Fibonnacci sequence.
You can check out the Python documentation on the
In this video, you’ll learn about the
functools module and learn about one higher order function
reduce() and two decorators,
lru_cache. Let’s get started with
from functools import reduce.
It’s important to include those parentheses to show that it actually evaluates left to right. It doesn’t evaluate just all at once. So, in an interview, if the interviewer asks you to somehow combine a list into one value, according to some rules, then
functools.reduce() should come to mind.
Let’s move on to the decorators. Let’s pretend we have a
Data class that takes in an
self.n = n, and then let’s define a
@property which is
def f(self) and does something that takes a long time. So, maybe
total = 0
for i in range(self.n):
for j in range(self.n):
for k in range(self.n):
total += i + j + k.
d = Data(200),
d.f. It’s evaluating this n-cubed function over and over again. Notice how this function doesn’t actually have any side effects, and so we can actually cache this value by using the
Let’s move on to another cached decorator. Imagine you’re writing the Fibonacci function. So, the Fibonacci series looks something like this. The zeroth at the Fibonacci number is
0, the first Fibonacci is
1, the next Fibonacci number is the previous two added together, and so on.
This is available in Python 3.2 and above. Wrap our function in
@lru_cache, save, exit. Now, when you call
fib(5), it actually caches those values, and then when you have to access it later on, it can access it immediately. So,
fib(100)—now, it takes a lot faster. And notice how, here, it actually stopped printing out after
1 were actually already cached, here.
That concludes the
functools video. As always, there are many more functions included in the module and I’ll link the documentation down below. In the next video, you’ll learn about the
doctest module and
Become a Member to join the conversation.