The single most useful Python Decorator @cache

Felipe F Garcia
The Dev Project
Published in
5 min readNov 10, 2021

--

Photo by Mikhail Nilov from Pexels

Python is well known for its simplicity and many resources that can help you.

Not only do we have many different resources in our community but we also have a lot of helpful resources inside Python standard libraries.

One that is really useful for example is a decorator named “cache”, and as the names say it is used to cache values.

This is all part of also one of the most helpful modules (this is how libraries are called in Python) which is the functools.

To see what else this module can offer check the documentation on this link: https://docs.python.org/3/library/functools.html

How this can speed up? The problem.

To test this we need a very simple problem so we can better understand what is happening.

For this, we will create a recursive function (loop) that will call itself multiple times.

We will try to calculate the factorial of a number.

Factorial of a whole number ’n’ is defined as the product of that number with every whole number till 1. For example, the factorial of 4 is 4×3×2×1, which is equal to 24

This is the code:

def factorial(n):
return n * factorial(n-1) if n else 1

--

--

Felipe F Garcia
The Dev Project

Backend Engineer 💻 Java 👾 Python 🐍 Top Writer in Medium at the topic Technology 🚀 With a mindset to help and share knowledge 📖.