def locally_cachedmethod(f): from collections import defaultdict def self_cache_fn(f_name): def cf(self): return self.__dict__.setdefault("_cache", defaultdict(lambda: LRUCache(128)))[f_name] return cf return cachedmethod(self_cache_fn(f.__name__), key=hash_key)(f)
def decorator(func: Callable) -> Callable: cache_attr = f'_{func.__name__}_cache' cache_type = getattr(cachetools, f'{method.upper()}Cache') cache_decorator = cachetools.cachedmethod(attrgetter(cache_attr)) cached_inner = cache_decorator(func) @wraps(func) def inner(first, *args, **kwargs): if not hasattr(first, cache_attr): setattr(first, cache_attr, cache_type(maxsize)) return cached_inner(first, *args, **kwargs) return inner
def test_typed_deprecated(self): with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") cachedmethod(lambda self: None, None)(lambda self: None) self.assertIs(w[-1].category, DeprecationWarning) with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") cachedmethod(lambda self: None, False)(lambda self: None) self.assertIs(w[-1].category, DeprecationWarning) with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") cachedmethod(lambda self: None, True)(lambda self: None) self.assertIs(w[-1].category, DeprecationWarning) with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") cachedmethod(lambda self: None, typed=None)(lambda self: None) self.assertIs(w[-1].category, DeprecationWarning)
def wrapper(func): return wraps(func)(cachedmethod(attrgetter(cache_prop), key=partial(hashkey, key))(func))
import operator from cachetools import LRUCache, cachedmethod from nameko_salesforce.api.client import ClientPool, ClientProxy from nameko_salesforce import constants cached = cachedmethod(operator.attrgetter('cache')) class NotFound(LookupError): pass def get_client(*args, **kwargs): pool = ClientPool(*args, **kwargs) return PushTopicsAPIClient(pool) class PushTopicsAPIClient(ClientProxy): """ Salesforce API client with helper method for managing PushTopic object """ NotFound = NotFound def __init__(self, pool): self.cache = LRUCache(maxsize=100) super().__init__(pool)
def cached(func): if attrgetter('cache') is not None: return cachedmethod(attrgetter('cache'))(func) else: return func
def cache_meta(func): return cachedmethod(lambda self: self.cache_meta, key=partial(hashkey, key))( func )