Python functools.cache Function

The functools.cache function in Python's functools module provides a decorator for memoizing function results. This can help improve performance by caching the results of expensive or frequently called functions.

Table of Contents

  1. Introduction
  2. functools.cache Function Syntax
  3. Examples
    • Basic Usage
    • Using with Recursive Functions
    • Using with Expensive Calculations
  4. Real-World Use Case
  5. Conclusion

Introduction

The functools.cache function is used to cache the results of function calls. This can be particularly useful for functions that are computationally expensive or called frequently with the same arguments. By caching the results, subsequent calls with the same arguments can return the cached result instead of recomputing it.

functools.cache Function Syntax

Here is how you use the functools.cache function:

import functools

@functools.cache
def func(args):
    # Function implementation
    pass

Parameters:

  • func: The function whose results are to be cached.

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.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

Using with Recursive Functions

Cache the results of a recursive function like Fibonacci.

Example

import functools

@functools.cache
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]

Using with Expensive Calculations

Cache the results of an expensive calculation.

Example

import functools
import time

@functools.cache
def expensive_computation(x):
    print(f"Computing {x}...")
    time.sleep(2)  # Simulate an expensive computation
    return x * x

print(expensive_computation(4))  # Output: Computing 4...
                                 #         16
print(expensive_computation(4))  # Output: 16 (cached result)

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.cache
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.cache function is used for caching function results, 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 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