Last active
November 7, 2016 18:26
-
-
Save ejm/6ea853e76b11ebe6d2c8567c478ada64 to your computer and use it in GitHub Desktop.
Quick setup to cache results of functions
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
# 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