Last active
August 29, 2015 14:10
-
-
Save sanpingz/a1f0acd9ac316f45d7bc to your computer and use it in GitHub Desktop.
function cache
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
__author__ = 'sanpingz' | |
__doc__ = '''Fucntion cache based on decorator, support expire and args''' | |
import time | |
cache = dict() | |
def cached(expire=0): | |
def _deco(func): | |
def __deco(*args, **kwargs): | |
ch = cache.get(func.__name__) or {} | |
if ch and ( | |
(expire > 0 and time.time() - ch.get('time') < expire) or | |
(expire <= 0 and args == ch.get('args') and kwargs == ch.get('kwargs')) | |
): | |
return ch.get('return') | |
ch['return'] = func(*args, **kwargs) | |
ch['time'] = time.time() | |
ch['args'] = args | |
ch['kwargs'] = kwargs | |
cache[func.__name__] = ch | |
return ch.get('return') | |
return __deco | |
return _deco | |
@cached(expire=3) | |
def foo(*args, **kwargs): | |
time.sleep(3) | |
return time.time() | |
@cached() | |
def bar(a, k=1): | |
time.sleep(3) | |
return str(a)+str(k) | |
if __name__ == '__main__': | |
print foo() | |
print foo() | |
time.sleep(3) | |
print foo() | |
print bar("a") | |
print bar("a") | |
print bar("b") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment