Python functools.lru_cache Function

The functools.lru_cache function in Python's functools module provides a decorator for caching the results of function calls using a Least Recently Used (LRU) strategy. This can help improve performance by storing results of expensive or frequently called functions and reusing them when the same inputs occur.

Table of Contents

  1. Introduction
  2. functools.lru_cache Function Syntax
  3. Examples
    • Basic Usage
    • Specifying the Cache Size
    • Using with Recursive Functions
    • Cache Information
  4. Real-World Use Case
  5. Conclusion

Introduction

The functools.lru_cache function is used to cache the results of function calls, improving performance by avoiding redundant calculations. It uses an LRU strategy, which means that it discards the least recently used items first when the cache reaches its maximum size.

functools.lru_cache Function Syntax

Here is how you use the functools.lru_cache function:

import functools

@functools.lru_cache(maxsize=128, typed=False)
def func(args):
    # Function implementation
    pass

Parameters:

  • maxsize: Optional. The maximum size of the cache. If set to None, the cache can grow without bound. The default is 128.
  • typed: Optional. If set to True, arguments of different types will be cached separately. The default is False.

Returns:

  • A decorated version of the input function with caching enabled.

Examples

Basic Usage

Cache the results of a simple function.

Example

import functools

@functools.lru_cache()
def add(a, b):
    print(f"Calculating {a} + {b}")
    return a + b

print(add(1, 2))  # Output: Calculating 1 + 2
                  #         3
print(add(1, 2))  # Output: 3 (cached result)
print(add(2, 3))  # Output: Calculating 2 + 3
                  #         5

Specifying the Cache Size

Specify the maximum size of the cache.

Example

import functools

@functools.lru_cache(maxsize=2)
def add(a, b):
    print(f"Calculating {a} + {b}")
    return a + b

print(add(1, 2))  # Output: Calculating 1 + 2
                  #         3
print(add(2, 3))  # Output: Calculating 2 + 3
                  #         5
print(add(3, 4))  # Output: Calculating 3 + 4
                  #         7
print(add(1, 2))  # Output: Calculating 1 + 2 (1 + 2 was evicted from cache)
                  #         3

Using with Recursive Functions

Cache the results of a recursive function like Fibonacci.

Example

import functools

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

print([fibonacci(n) for n in range(10)])  # Output: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

Cache Information

Get information about the cache usage.

Example

import functools

@functools.lru_cache(maxsize=2)
def add(a, b):
    return a + b

add(1, 2)
add(2, 3)
add(3, 4)
print(add.cache_info())  # Output: CacheInfo(hits=0, misses=3, maxsize=2, currsize=2)

Real-World Use Case

Web Page Caching

Cache the results of fetching web pages to avoid redundant network requests.

Example

import functools
import requests

@functools.lru_cache(maxsize=32)
def fetch_page(url):
    print(f"Fetching {url}...")
    response = requests.get(url)
    return response.text

url = 'https://example.com'
print(fetch_page(url))  # Output: Fetching https://example.com...
                        #         (page content)
print(fetch_page(url))  # Output: (cached result)

Conclusion

The functools.lru_cache function is used for caching the results of function calls, improving performance by avoiding redundant computations. It is particularly useful for recursive functions, expensive calculations, and tasks where results are repeatedly needed. Proper usage can significantly enhance the efficiency and responsiveness of your code.

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare