Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

python cache

from functools import lru_cache


# store a maximum of 32 value cached
@lru_cache(maxsize=32)
def fib(n):
    if n < 2:
        return n
    return fib(n-1) + fib(n-2)

#clear cache
fib.cache_clear()
Comment

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
Comment

PREVIOUS NEXT
Code Example
Python :: change item in list python 
Python :: seaborn Using the dark theme python 
Python :: print from within funciton with multiprocessing 
Python :: raku fibonacci 
Python :: python print without new lines 
Python :: print A to z vy using loop in python 
Python :: how to make dictionary in python 
Python :: how to encrypt text in python 
Python :: add to python list 
Python :: remove item list python 
Python :: round list python 
Python :: python alphabetical order 
Python :: how to get key value in nested dictionary python 
Python :: Python program to count positive and negative numbers in a list 
Python :: how to get input from pyqt line edit 
Python :: numpy divide with exception 
Python :: flask error handling 
Python :: python extract list from string 
Python :: python threading 
Python :: DLL Injection in python 
Python :: Python program to print negative numbers in a list 
Python :: how to make an int into a string python 
Python :: link in embed discord.py 
Python :: load pt file 
Python :: sum of list in python 
Python :: keras maxpooling1d 
Python :: Python RegEx Escape – re.escape() 
Python :: add two column values of a datframe into one 
Python :: Print First 10 natural numbers using while loop 
Python :: python logging to syslog linux 
ADD CONTENT
Topic
Content
Source link
Name
3+9 =