Skip to content

Instantly share code, notes, and snippets.

@scott2b
Forked from mminer/cachedecorator.py
Created February 14, 2022 23:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scott2b/1c7c89f500173fb120179c78b2f387e7 to your computer and use it in GitHub Desktop.
Save scott2b/1c7c89f500173fb120179c78b2f387e7 to your computer and use it in GitHub Desktop.
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.
value = func(*args, **kwargs)
value_json = json.dumps(value)
redis.set(key, value_json)
else:
# Skip the function entirely and use the cached value instead.
value_json = result.decode('utf-8')
value = json.loads(value_json)
return value
return wrapper
# Usage:
@cached
def my_great_function():
# The below calculation will run the first time this function is called.
# On subsequent runs the result will be pulled from the cache instead.
return list(range(10000))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment