dhp.cache package

Module contents

Caching mechanisms that can be used as is or subclassed to enable specialization. view the source

exception dhp.cache.CacheKeyUnhashable

Bases: exceptions.Exception

Exception raised when the key given is not hashable.

It is a replacement for the normal TypeError that would be raised in this situation to keep the exception logcially separated.

Parameters:message (str) – Human readable string describing the exception.
message

str – Human readable string describing the exception.

exception dhp.cache.CacheMiss

Bases: exceptions.Exception

Exception raised when requested key can not be found.

Any SimpleCache operation that requires a key: .get, .put and .invalidate, and the key supplied can not be found while raise a CacheMiss. It is a replacement for the normal KeyError but is a logically separate exception.

Parameters:message (str) – Human readable string describing the exception.
message

str – Human readable string describing the exception.

Examples

>>> from dhp.cache import SimpleCache, CacheMiss
>>> scache = SimpleCache()
>>> try:
>>>     value = scache.get(key='foo')
>>> except CacheMiss:
>>>     # do something meaningful like set value to a default
>>>     # or run your expensive operation.
>>>     pass
class dhp.cache.SimpleCache

Bases: object

A simplistic cache mechanism.

SimpleCache is an in-memory dictionary based caching mechanism. It includes cache stats.

Examples

>>> from dhp.cache import SimpleCache
>>> scache = SimpleCache()
>>> scache.put(key='foo', value='bar')
>>> scache.get(key='foo')
'bar'

A key can be any Python hashable object, the restrictions on value are the same as for a Python dict – since that is the underlying mechansim.

get(key)

Return the cached entry indicated by key or raise CacheMiss

Parameters:

key (hashable object) – The cache key to retrieve.

Returns:

The object associated with key.

Raises:
invalidate(key)

Invalidate an element of the cache.

Parameters:

key (hashable object) – The key to remove from the cache.

Raises:
put(key, value)

Cache the value with key.

Parameters:
  • key (hashable object) – The key to associate with the value. Keys are unique. The most recent .put call replaces the existing value, if any.
  • value (object) – The value to cache.
Raises:

CacheKeyUnhashable – if the key is not hashable.

stats

(property) Returns a dictionary with cache stats.

Returns:
a 4 element dictionary consisting of cache_size,
cache_hits, cache_misses and cache_invalidated.
Return type:(dict)