Skip to content

Instantly share code, notes, and snippets.

@ejm
Last active November 7, 2016 18:26
Show Gist options
  • Save ejm/6ea853e76b11ebe6d2c8567c478ada64 to your computer and use it in GitHub Desktop.
Save ejm/6ea853e76b11ebe6d2c8567c478ada64 to your computer and use it in GitHub Desktop.
Quick setup to cache results of functions
# cache.py - Quick setup to cache results of functions
# Copyright 2016 Evan Markowitz - Licensed under MIT
from datetime import datetime as dt
from datetime import timedelta as td
class CachedResult(object):
def __init__(self, func_, timeout):
""" Cache the results of `func` for `timeout` seconds """
self.func_ = func_
self.timeout = td(seconds=timeout)
self.last_call = dt.min
self.result = None
def __call__(self, *args, **kwargs):
if (self.last_call + self.timeout) < dt.now():
self.result = self.func_(*args, **kwargs)
self.last_call = dt.now()
return self.result
def cached(timeout):
""" Decorate a function to cache its results """
def _cached(func):
return CachedResult(func, timeout)
return _cached
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment