Answers for "python caching"

0

lru cache python

from functools import lru_cache 
  
@lru_cache(maxsize = 100) 
def myfunc(args):
  // do something
Posted by: Guest on January-21-2021
1

python function cache

# Example use - Decorator code below -----------------------------
import time

@cache(ttl=timedelta(minutes=3), max_entries=300)
def add(a, b):
    time.sleep(2)
    return a + b

@cache()
def substract(a, b):
    time.sleep(2)
    return a - b
  
  
# Decorator code -----------------------------
from datetime import datetime, timedelta

def cache(**kwargs):
  def decorator(function):
    # static function variable for cache, lazy initialization
    try: function.cache
    except: function.cache = {}
    def wrapper(*args):
        # if nothing valid in cache, insert something
        if not args in function.cache or datetime.now() > function.cache[args]['expiry']:
            if 'max_entries' in kwargs:
                max_entries = kwargs['max_entries']
                if max_entries != None and len(function.cache) >= max_entries:
                    now = datetime.now()
                    function.cache = { key: function.cache[key] for key in function.cache.keys() if function.cache[key]['expiry'] > now }
                    # if nothing is expired that is deletable, delete the first
                    if len(function.cache) >= max_entries:
                        del function.cache[next(iter(function.cache))]
            function.cache[args] = {'result': function(*args), 'expiry': datetime.max if 'ttl' not in kwargs else datetime.now() + kwargs['ttl']}

        # answer from cache
        return function.cache[args]['result']
    return wrapper
  return decorator
Posted by: Guest on June-17-2021

Python Answers by Framework

Browse Popular Code Answers by Language