Created
January 23, 2021 11:05
-
-
Save h0rn3t/69697974a1e487f90041d5401e508da4 to your computer and use it in GitHub Desktop.
timed_lru_cache
This file contains hidden or 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
from functools import lru_cache, wraps | |
from datetime import datetime, timedelta | |
def timed_lru_cache(seconds: int, maxsize: int = 128): | |
def wrapper_cache(func): | |
func = lru_cache(maxsize=maxsize)(func) | |
func.lifetime = timedelta(seconds=seconds) | |
func.expiration = datetime.utcnow() + func.lifetime | |
@wraps(func) | |
def wrapped_func(*args, **kwargs): | |
if datetime.utcnow() >= func.expiration: | |
func.cache_clear() | |
func.expiration = datetime.utcnow() + func.lifetime | |
return func(*args, **kwargs) | |
return wrapped_func | |
return wrapper_cache |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment