Memoization and encapsulation

drewp at bigasterisk.com drewp at bigasterisk.com
Wed Jan 4 12:16:36 EST 2006


But while we're at it, how about that unhashable object problem?

@memoised
def func(x, i):
    return x[i]

L = [1,2,3]
print func(L, 1)   # TypeError: list objects are unhashable

What's the deal? My func can certainly be memoized (but possibly with a
slower lookup depending on how many args are "unhashable"). In fact,
list objects *could* be hashed:

class HashableList(list):
    def __hash__(self):
        return 0

L = HashableList([1,2,3])
print func(L, 1)

That's both correct and useful. I've written fancier memoize()
implementations in the past that added a __hash__ to incoming objects
that didn't have any, although handling lists would be a tricky case.
In my cases, most arguments could be hashed and the values that
couldn't were part of very small sets, so I actually had very few hash
table collisions.

I think python is broken here-- why aren't lists hashable, or why isn't
there a straightforward way to make memoised() work?




More information about the Python-list mailing list