Python Tutorial

Tuesday, February 19, 2013

Python implement caching - using decorator

Python custom caching using decorator.

All source code available on github

from functools import wraps

def custom_memoize(func):
    cache = {}
    @wraps(func)
    def wrapper(*args):
        if args in cache:
            print "Returning cache data"
            return cache[args]
        # If result not found then call the function
        result = func(*args)
        cache[args] = result
        return result

    return wrapper

@custom_memoize
def add(x,y):
    return x+y

print add(1,2)
print add(2,5)
print add(1,2)
print add(2,5)

Output:
3
7
Returning cache data
3
Returning cache data
7

0 comments:

Post a Comment