Categories
Python Answers

How to simply cache function return values with Python?

Spread the love

Sometimes, we want to simply cache function return values with Python.

In this article, we’ll look at how to simply cache function return values with Python.

How to simply cache function return values with Python?

To simply cache function return values with Python, we can use the lru_cache decorator.

For instance, we write

from functools import lru_cache

@lru_cache(maxsize=None)
def fib(n):
    if n < 2:
        return n
    return fib(n-1) + fib(n-2)

to create the fib fibonacci sequence function.

And we use the lru_cache decorator on it to cache the returned values of fib.

Conclusion

To simply cache function return values with Python, we can use the lru_cache decorator.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *