Created
October 10, 2015 00:38
-
-
Save mayli/0650c71cd2a1d6c3a0ab to your computer and use it in GitHub Desktop.
Cache Manager
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 threading | |
import collections | |
import logging | |
class CacheManager(object): | |
_lock = threading.RLock() | |
_cache = dict() | |
_cache_lock = collections.defaultdict(threading.Lock) | |
@staticmethod | |
def get(function, *args, **kwargs): | |
cache_hash = "%s_%s_%s" % (function, args, kwargs) | |
cache_lock = None | |
with CacheManager._lock: | |
cache_lock = CacheManager._cache_lock[cache_hash] | |
with cache_lock: | |
if cache_hash not in CacheManager._cache: | |
try: | |
result = function(*args, **kwargs) | |
CacheManager._cache[cache_hash] = result | |
except: | |
logging.exception("Exception in running %s(%s, %s)", function, args, kwargs) | |
raise | |
return CacheManager._cache[cache_hash] | |
def test(): | |
func = lambda x: x | |
def bad_func(msg, no_raise=False): | |
if not no_raise: | |
raise StandardError(msg) | |
return msg | |
print CacheManager.get(func, 2) | |
print CacheManager.get(bad_func, msg="OK", no_raise=True) | |
print CacheManager.get(bad_func, msg="NO!") | |
if __name__ == '__main__': | |
test() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment