Created
January 30, 2021 22:52
-
-
Save tomekzaw/0af83875142fa54292afb867dd35a8c2 to your computer and use it in GitHub Desktop.
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
from dataclasses import dataclass | |
from datetime import datetime, timedelta | |
from typing import Generic, TypeVar, Callable, Optional | |
T = TypeVar('T') | |
@dataclass | |
class Cache(Generic[T]): | |
func: Callable[[], T] | |
interval: timedelta | |
_value: Optional[T] = None | |
_last_update_time: Optional[T] = None | |
def get(self) -> T: | |
if self._last_update_time is None or self._now() - self._last_update_time >= self.interval: | |
self.update() | |
return self._value | |
def update(self) -> None: | |
self._value = self.func() | |
self._last_update_time = self._now() | |
def _now(self) -> datetime: | |
return datetime.now() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment