Last active
December 5, 2018 02:11
-
-
Save harel/9ced5ed51b97a084dec71b9595565a71 to your computer and use it in GitHub Desktop.
Decorator for using dicts/lists with python LRU Cache
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
def hashable_lru(func): | |
cache = lru_cache(maxsize=1024) | |
def deserialise(value): | |
try: | |
return json.loads(value) | |
except Exception: | |
return value | |
def func_with_serialized_params(*args, **kwargs): | |
_args = tuple([deserialise(arg) for arg in args]) | |
_kwargs = {k: deserialise(v) for k, v in kwargs.items()} | |
return func(*_args, **_kwargs) | |
cached_function = cache(func_with_serialized_params) | |
@wraps(func) | |
def lru_decorator(*args, **kwargs): | |
_args = tuple([json.dumps(arg, sort_keys=True) if type(arg) in (list, dict) else arg for arg in args]) | |
_kwargs = {k: json.dumps(v, sort_keys=True) if type(v) in (list, dict) else v for k, v in kwargs.items()} | |
return cached_function(*_args, **_kwargs) | |
lru_decorator.cache_info = cached_function.cache_info | |
lru_decorator.cache_clear = cached_function.cache_clear | |
return lru_decorator |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Inspired by your idea, I created a more generic version:
https://gist.github.com/adah1972/f4ec69522281aaeacdba65dbee53fade