I'm trying to write a generic memoization function in python 2.7 (no issue in 3.x)
def init_memoize():
fns = dict()
def memoize(fn, *args):
if fn not in fns:
fns[fn] = dict()
print type(args) # prints "<type 'tuple'>"
print args in fns[fn] # throws the error
if args not in fns[fn]:
fns[fn][args] = fn(*args)
return fns[fn][args]
return memoize
memoize = init_memoize()
memoize(sorted, range(5))
memoize(sorted, range(10))
When I try and run this code, I get an error TypeError: unhashable type: 'list'
at the noted line, but immediately before, I verify that the type of args is a hashable tuple.
Can someone clarify why the type of args
changes?
A tuple with a list inside it is still unhashable for the same reason that a list is unhashable.