Skip to content

Instantly share code, notes, and snippets.

@Suor
Created June 12, 2014 11:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Suor/1f9125fabe12ce9b6a4e to your computer and use it in GitHub Desktop.
Save Suor/1f9125fabe12ce9b6a4e to your computer and use it in GitHub Desktop.
Using @decorator with methods
# Say we have this
class BaseCache(object):
def cached(self, timeout=None):
"""A decorator for caching function calls"""
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
cache_key = get_key(func, args, kwargs)
try:
result = self.get(cache_key)
except CacheMiss:
result = func(*args, **kwargs)
self.set(cache_key, result, timeout)
return result
return wrapper
return decorator
# We can make it look this with a decorator
class BaseCache(object):
@decorator
def cached(call, self, timeout=None):
"""A decorator for caching function calls"""
cache_key = get_key(call._func, call._args, call._kwargs)
try:
result = self.get(cache_key)
except CacheMiss:
result = call()
self.set(cache_key, result, timeout)
return result
# Basic idea: self is just a decorator argument
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment