Memoizing using decorators in Python

I came across this topic during one of our developer’s stand-up griefs. Digging into this topic led me to discover the concept of memoization in computing.

Basically to cut the story short, this is nothing but caching in its simplest terms. The only difference lies in the use of this caching.

I have compiled a way in which any object can be memoized.

import collections 
from functools import wraps
def memoize(obj): 
cache = obj.cache = {}
def memoizer(*args, **kwargs):
print "Initial cache: " + str(cache)
        for _1 in args: 
if not isinstance(_1, collections.Hashable):
return obj(*args, **kwargs)
            if (str(args) + str(kwargs)) in obj.cache: 
print "Found in cache"
return obj.cache[str(args) + str(kwargs)]
print "Not found in cache"
value = obj(*args, **kwargs)
obj.cache[str(args) + str(kwargs)] = value
print "Updated cache: " + str(obj.cache)
return value
    return memoizer

Use this as a decorator for your function or class by simply appending @memoize before the definition.

For further reading, refer:


Originally published at on August 20, 2015.