@lru_cache — caching function results.
1from functools import lru_cache, cache23@lru_cache(maxsize=128)4def fibonacci(n):5 if n < 2:6 return n7 return fibonacci(n-1) + fibonacci(n-2)89fibonacci(100) # Fast!1011# Basic cache (Python 3.9+)12@cache13def expensive_function(x):14 return x ** 21516# Custom cache17from cachetools import TTLCache1819cache = TTLCache(maxsize=100, ttl=300) # 5 minutes2021@cached(cache=cache)22def get_user(user_id):23 return db.get_user(user_id)2425# Statistics26print(fibonacci.cache_info())27fibonacci.cache_clear() # Clear2829# Django cache30from django.core.cache import cache3132def get_products():33 data = cache.get("products")34 if data is None:35 data = Product.objects.all()36 cache.set("products", data, 300) # 5 minutes37 return data
Strategies: