Skip to content

Instantly share code, notes, and snippets.

@blakev
Created July 18, 2014 20:50
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 blakev/7b7fbc8af31b42699ce0 to your computer and use it in GitHub Desktop.
Save blakev/7b7fbc8af31b42699ce0 to your computer and use it in GitHub Desktop.
Python Class @cache decorator
import time
import random
DEFAULT_CACHE_TIME = 5 # seconds
class A:
def __init__(self):
pass
def cache(*args):
def _cache(func):
def wrapper(self, *args, **kwargs):
now = time.time()
if wrapper.last_res is None or now > wrapper.init + cache_time:
wrapper.last_res = func(self, *args, **kwargs)
wrapper.init = time.time()
return wrapper.last_res
wrapper.init = time.time()
wrapper.last_res = None
return wrapper
if len(args) == 1 and callable(args[0]):
cache_time = DEFAULT_CACHE_TIME
return _cache(args[0])
else:
cache_time = args[0]
return _cache
@cache(2)
def test(self, a):
return random.randint(0, 100)
X = A()
while True:
print X.test(2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment