Friday, September 30

Tag: caching

An example of a Python decorator to simplify caching a function’s result.

"""An example of a cache decorator.""" import json from functools import wraps from redis import StrictRedis redis = StrictRedis() def cached(func): """ Decorator that caches the results of the function call. We use Redis in this example, but any cache (e.g. memcached) will work. We also assume that the result of the function can be seralized as JSON, which obviously will be untrue in many situations. Tweak as needed. """ @wraps(func) def wrapper(*args, **kwargs): # Generate the cache key from the function's arguments. key_parts = [func.__name__] + list(args) key = '-'.join(key_parts) result = redis.get(key) if result is None: # Run the function and cache the result for next time. ...