Created
June 12, 2014 11:08
-
-
Save Suor/1f9125fabe12ce9b6a4e to your computer and use it in GitHub Desktop.
Using @decorator with methods
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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