Skip to content

Instantly share code, notes, and snippets.

@tomekzaw
Created January 30, 2021 22:52
Show Gist options
  • Save tomekzaw/0af83875142fa54292afb867dd35a8c2 to your computer and use it in GitHub Desktop.
Save tomekzaw/0af83875142fa54292afb867dd35a8c2 to your computer and use it in GitHub Desktop.
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