Created
September 19, 2022 15:45
-
-
Save Sanix-Darker/c139022852397a97246c20630dc4f8ac to your computer and use it in GitHub Desktop.
[PYTHON]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
import time | |
from functools import lru_cache, wraps | |
from datetime import datetime, timedelta | |
def timed_lru_cache(seconds: int, maxsize: int = None): | |
def wrapper_cache(func): | |
print('I will use lru_cache') | |
func = lru_cache(maxsize=maxsize)(func) | |
print('I\'m setting func.lifetime') | |
func.lifetime = timedelta(seconds=seconds) | |
print('I\'m setting func.expiration') | |
func.expiration = datetime.utcnow() + func.lifetime | |
@wraps(func) | |
def wrapped_func(*args, **kwargs): | |
print('Check func expiration') | |
print(f'datetime.utcnow(): {datetime.utcnow()}, func.expiration: {func.expiration}') | |
if datetime.utcnow() >= func.expiration: | |
print('func.expiration lru_cache lifetime expired') | |
func.cache_clear() | |
func.expiration = datetime.utcnow() + func.lifetime | |
return func(*args, **kwargs) | |
return wrapped_func | |
return wrapper_cache | |
@timed_lru_cache(20) | |
def get_article_from_server(url): | |
print("Fetching article from server over Internet...") | |
with urllib.request.urlopen(url) as req: | |
text = req.read(1200).decode('utf-8') | |
return text.count(word) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment