How to write python decorator for caching?

by raphael_tillman , in category: Third Party Scripts , 2 months ago

How to write python decorator for caching?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by arnoldo.moen , a month ago

@raphael_tillman 

Here is an example of how you can write a Python decorator for caching:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
import functools

def cache(func):
    cached_results = {}

    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        key = (args, frozenset(kwargs.items()))
        if key not in cached_results:
            cached_results[key] = func(*args, **kwargs)
        return cached_results[key]

    return wrapper


You can then apply this decorator to any expensive function that you want to cache the results of. Here's an example of using the cache decorator:

1
2
3
4
5
6
7
8
@cache
def fibonacci(n):
    if n <= 1:
        return n
    else:
        return fibonacci(n-1) + fibonacci(n-2)

print(fibonacci(10)) # This will cache the result of fibonacci(10)


This decorator will store the results of function calls in a dictionary and return the cached result if the same inputs are provided again. This can be useful for optimizing performance in situations where a function is called repeatedly with the same inputs.