Caching in Python con lru_cache
Il caching può essere fondamentale in tante applicazioni.
In Python abbiamo diverse possibilità, tra cui il caching incluso nel modulo functools.
Tra i vari sistemi disponibili abbiamo LRU:
Least Recently Used (LRU) -> Evicts the least recently used entry -> Recently used entries are most likely to be reused
Un buon esempio è quando dobbiamo richiamare una API usando gli stessi parametri:
import requests
from functools import lru_cache
@lru_cache(maxsize=32)
def get_weather(search):
response = requests.get(f"https://www.mattepuffo.com/api/book/get.php?t={search}")
return response.json()
print(get_weather("fondazione"))
print(get_weather("fondazione"))
Oppure può essere utile per funzioni che eseguono le stesse query in maniera ripetuta; per funzioni ricorsive, ecc.
Enjoy!
python functools lru_cache
Commentami!