here is my effort in writing a helper decorator module:
# -*- coding: utf8 -*-
import time
def timer(func):
def timed(*args, **kwargs):
init = time.clock()
result = func(*args, **kwargs)
print (time.clock()-init)*1000, 'ms'
return result
return timed
class memo(object):
def __init__(self, func):
self.func = func
self.memo = {}
self.memohit = 0
def memoizedf(self, *args):
key = tuple(args)
print key
lookup = self.memo.setdefault(key, None)
if lookup:
self.memohit += 1
return lookup
result = self.func(*args)
self.memo[key]=result
return result
def __call__(self, *args):
return self.memoizedf(*args)
so, usage:
@timer
def foo():
print 'foo'
'foo'
00023.1231203879 ms
@memo
def bar(fooobject):
print fooobject
the problem comes here:
>>bar({'foo':'bar'})
traceback : ...........
lookup = self.memo.setdefault(key, None)
TypeError: unhashable type: 'dict'
every input of list, dict, or other mutable from collections would invoke such error. I tried tupling all args, but apparently this didn't help. How should I rewrite my code in order to have my decorator to work with any(well, just dict, list, tuple, set, int, string... would be ok) kind of input?