I am trying to use lru_cache
in Python3 to speed up common queries into our Salesforce database. Below is the relevant code that is supposed to
- a) convert non-hashable arguments to hashable ones, and
- b) enable the LRU cache for those objects.
When I try this code, the cache works for calling the functions with no arguments, but it doesn't seem to cache the function calls with arguments. Also, I am not sure of how to order the decorators for the decorated functions.
Note, I am using a class here with class and static methods so I can override the get
and get_all
methods for different subclasses of Resource
.
Please explain what I am doing wrong or could be doing better.
from functools import lru_cache
from functools import wraps
class Resource(object):
def hash_dict(func):
"""Transform mutable dictionnary
Into immutable
Useful to be compatible with cache
"""
class HDict(dict):
def __hash__(self):
return hash(frozenset(self.items()))
@wraps(func)
def wrapped(*args, **kwargs):
args = tuple([HDict(arg) if isinstance(arg, dict) else arg for arg in args])
kwargs = {}
for k, v in kwargs.items():
if isinstance(v, dict):
kwargs[k] = HDict(v)
elif isinstance(v, list):
kwargs[k] = tuple(v)
else:
kwargs[k] = v
return func(*args, **kwargs)
return wrapped
@staticmethod
@hash_dict
@lru_cache
def get(cls, resource_id, lang='en', fields=None):
pass
@classmethod
@hash_dict
@lru_cache
def get_all(cls, lang='en', filters=None, fields=None):
pass