I have a memoization decorator that looks like this:
def memoize(obj):
from functools import wraps
cache = {}
@wraps(obj)
def memoizer(*args, **kwargs):
if args not in cache:
cache[args] = obj(*args, **kwargs)
return cache[args]
return memoizer
However, I'm not sure this function works properly because it seems like to me it recreates cache
as an empty dictionary every time the decorated function is called. When I test it with a simple fibonacci function, it does appear to memoize correctly. So is cache
not recreated every time?
The python wiki has a version that includes this line:
cache = obj.cache = {}
So I am not sure what this does. I guess that python functions are objects so it is creating a new attribute associated with the function and is publically available/usable every time the function is called.
In either version, if I make repeated calls to the function, as in a recursive definition or just through repeated calls, how is the cache treated? Is it associated with the function, does it become a "global" variable, or something else?