I'm trying to write python decorator for memoize. I have few questions.
- How does @memoize translate to memoize class's call function?
- Why does init expect an argument.
- Where is the cache stored? Is it associated with each and every function or it's a global variable? i.e Will there be two cache objects if i use @memoize for multiple functions.
..
class memoize:
def __init__(self):
self.cache = {}
def __call__(self, function):
def wrapper(*args, **kwargs):
key = str(function.__name__) + str(args) + str(kwargs)
if key in cache:
return cache[key]
else:
value = function(*args, **kwargs)
cache[key] = value
return value
return wrapper
@memoize
def fib(n):
if n in (0, 1):
return 1
else:
return fib(n-1) + fib(n-2)
for i in range(0, 10):
print(fib(i))
I'm getting compilation error.
Traceback (most recent call last):
File "memoize.py", line 17, in <module>
@memoize
TypeError: __init__() takes exactly 1 argument (2 given)
lru_cachedecorator.