Skip to content

Instantly share code, notes, and snippets.

@Ari24-cb24
Last active May 22, 2022 08:14
Show Gist options
  • Save Ari24-cb24/f9334c5c751d238078a26374ed25a423 to your computer and use it in GitHub Desktop.
Save Ari24-cb24/f9334c5c751d238078a26374ed25a423 to your computer and use it in GitHub Desktop.
Python Method Caching with specified time
import time
def time_cache(ttl: int):
def decorator(func):
ttls = {}
return_cache = {}
def wrapper(*args, **kwargs):
key = (*args,) + tuple([(k, v) for k, v in kwargs.items()])
if key not in ttls:
ttls[key] = time.time() - ttl - ttl
if time.time() > ttls[key] + ttl:
result = func(*args, **kwargs)
return_cache[key] = result
ttls[key] = time.time()
return result
else:
return return_cache[key]
return wrapper
return decorator
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment