Caching for humans
Python Makefile
Latest commit 4f0d4e2 Nov 20, 2016 @jneen committed on GitHub Merge pull request #5 from utgwkk/localcache-with-expiration
Implement LocalCache with expiration times option

cache: caching for humans


pip install cache


import pylibmc
from cache import Cache

backend = pylibmc.Client([""])

cache = Cache(backend)

def some_expensive_method():
    return 42

# writes 42 to the cache

# reads 42 from the cache

# re-calculates and writes 42 to the cache

# get the cached value or throw an error
# (unless default= was passed to @cache(...))


Options can be passed to either the Cache constructor or the decorator. Options passed to the decorator take precedence. Available options are:

enabled    If `False`, the backend cache will not be used at all,
           and your functions will be run as-is, even when you call
           `.cached()`.  This is useful for development, when the
           function may be changing rapidly.
           Default: True

bust       If `True`, the values in the backend cache will be
           ignored, and new data will be calculated and written
           over the old values.
           Default: False

default    If given, `.cached()` will return the given value instead
           of raising a KeyError.

The remaining options, if given, will be passed as keyword arguments to the backend's set method. This is useful for things like expiration times - for example, using pylibmc:

@cache("some_key", time=1000)
def expensive_method():
    # ...

Local Caches

Cache provides two "fake" caches for local development without a backend cache: LocalCache and NullCache. LocalCache uses a dictionary in place of a backend cache, and NullCache is a noop on set and always returns None on get.

The difference between passing enabled=False to the cache and using NullCache comes in when you use the .cached() method. If the cache is disabled, .cached() will run the underlying function, but NullCache will throw a KeyError as if the key was not present.


If you're a Ruby user, check out the analogous Cacher library for Ruby