"""
Basic implementations of the AbstractCache interface
"""
from fictive.cache.abstract import AbstractCache
[docs]class InstanceVariableCache(AbstractCache):
"""
Cache implementation using an instance variable as the backing store
(each instance will have a separate backing store)
"""
def _read_impl(self, *args, **kwargs):
try:
return self._value
except AttributeError:
raise self.CacheMissError()
def _set_impl(self, value, *args, **kwargs):
# pylint: disable=attribute-defined-outside-init
self._value = value
def _delete_impl(self, *args, **kwargs):
try:
del self._value
return True
except AttributeError:
return False
[docs]class ClassVariableCache(AbstractCache):
"""
Cache implementation using a class attribute as the backing store
(instances share a common backing store keyed by `cache_name`)
"""
# pylint: disable=protected-access
_VALUE_MAP = {}
[docs] def __init__(self, cache_name='default', *args, **kwargs):
"""
:param str cache_name: shared cache cache_name this instance should use
"""
self.cache_name = cache_name
super(ClassVariableCache, self).__init__(*args, **kwargs)
def _read_impl(self, *args, **kwargs):
try:
return type(self)._VALUE_MAP[self.cache_name]
except KeyError:
raise self.CacheMissError()
def _set_impl(self, value, *args, **kwargs):
type(self)._VALUE_MAP[self.cache_name] = value
def _delete_impl(self, cache_value, *args, **kwargs):
try:
del type(self)._VALUE_MAP[self.cache_name]
return True
except KeyError:
return False