API

dcache

dcache.cache = <dcache.dcache.Dcache object>

Default in-memory cache

>>> from dcache import cache
...
>>> @cache
... def slow_function():
...     ...
...
class dcache.dcache.Dcache(backend=None, key=<function dhash>)[source]

Bases: object

Parameters
  • backend (dcache.backends.Base, optional) – The backend used to cache, defaults to dcache.backends.InMemory

  • key (function, optional) – A function that will receive cached function, args and kwargs, and should return a unique key that will be used to distinguish the cached results, defaults to dcache.keys.dhash()

Backends

class dcache.backends.Base[source]

Bases: object

Base backend to be inherit by custom backends.

>>> from dcache.backends import Base as BaseBackend
...
>>> class CustomBackend(BaseBackend):
...    def __init__(self):
...        self.cache = {}
...
...    def __getitem__(self, key):
...        return self.cache[key]
...
...    def __setitem__(self, key, value):
...        self.cache[key] = value
...
>>> backend = CustomBackend()
>>> backend['key'] = 'value'
>>> backend['key']
'value'
__getitem__(key)[source]

Return the value from the backend, if exists, if not raises an exception.

Parameters

key – The key that will be used to lookup for the cache.

Raises

NotExistError – raises when the key was not found in the backend.

Returns

cached result

__setitem__(key, value)[source]

Save the value into the backend.

Parameters
  • key – The key that will be used to save the value.

  • value – The value that will be cached.

class dcache.backends.InMemory[source]

Bases: dict, Base

InMemory backend uses a dict to save the cached values.

>>> from dcache.backends import InMemory as InMemoryBackend
...
>>> backend = InMemoryBackend()
>>> backend['key'] = 'value'
>>> backend['key']
'value'
__getitem__(*args, **kwargs)[source]

Override dict.__get__ to raise dcache.exceptions.NotExistError instead of the default KeyError.

Raises

NotExistError – raises when the key was not found in the backend.

Returns

cached result

Exceptions

exception dcache.exceptions.NotExistError[source]

Bases: KeyError

Exception raised when the value is not found in the backend.

Keys

dcache.keys.dhash(func, *args, **kwargs)[source]

Create a unique hash from the union of func, args and kwargs.

Serializers