141. Decorators for Caching Results
1. Basic Caching with lru_cache
lru_cachefrom functools import lru_cache
@lru_cache(maxsize=None) # Unlimited cache size
def expensive_computation(n):
print(f"Computing {n}...")
return n * n
# First call, performs the computation
print(expensive_computation(4))
# Second call, retrieves from cache
print(expensive_computation(4)) Output:
Computing 4...
16
16Explanation:
2. Caching with lru_cache with a Limited Cache Size
lru_cache with a Limited Cache SizeOutput:
Explanation:
3. Caching with Custom Decorators
Output:
Explanation:
4. Caching Function Results with lru_cache for Fibonacci Numbers
lru_cache for Fibonacci NumbersOutput:
Explanation:
5. Caching with Function Arguments as Keys
Output:
Explanation:
6. Memoization for Repeated Function Calls
Output:
Explanation:
7. Clearing the Cache Manually
Output:
Explanation:
8. Conditional Caching
Output:
Explanation:
9. Caching Results in Web Applications
Output:
Explanation:
10. Custom Cache Timeout
Output:
Explanation:
Conclusion:
Previous140. Creating and Handling Custom Context ManagersNext142. Using dataclasses for Structured Data
Last updated