Skip to main content

Posts

Showing posts with the label caching

Function Caching in Python

  Learning Sections          show Function Caching in Python Function caching is a technique used to store the results of expensive function calls and reuse those results when the same inputs occur again. Python's functools module provides a built-in way to cache function results using the lru_cache decorator. Using lru_cache from functools The lru_cache decorator caches the results of a function based on its inputs. It uses a Least Recently Used (LRU) caching strategy to manage the cache size: from functools import lru_cache # Apply the lru_cache decorator @lru_cache (maxsize= 128 ) def fib ( n ): if n == 0 : return 0 elif n == 1 : return 1 else : return fib ( n - 1 ) + fib ( n - 2 ) # Call the cached function print ( fib ( 10 )) In this example, the Fibonacci function results are cached, so repeated calls with the same input are faster. ...