Last active
May 22, 2022 08:14
-
-
Save Ari24-cb24/f9334c5c751d238078a26374ed25a423 to your computer and use it in GitHub Desktop.
Python Method Caching with specified time
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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