Caching a Function
2 August 2025
Caching a function can speed up function requests. Two possible solutions.
Solution
""" cache.py """
# usage: python3 cache.py
def cache(function):
""" decorator to cache function """
store = {}
def wrapper(*args):
""" retrieve value or calculate it """
if args not in store:
store[args] = function(*args)
return store[args]
return wrapper
@cache
def fibonacci(num):
""" calculate num'th fibonacci number """
return num if num < 2 else fibonacci(num - 1) + fibonacci(num - 2)
print(fibonacci(42))
Solution
""" cache_module.py """
# usage: python3 cache_module.py
from functools import cache
@cache
def fibonacci(num):
""" calculate num'th fibonacci number """
return num if num < 2 else fibonacci(num - 1) + fibonacci(num - 2)
print(fibonacci(42))