Memoization and encapsulation
Mike Meyer
mwm at mired.org
Wed Jan 4 16:43:03 EST 2006
drewp at bigasterisk.com writes:
> class HashableList(list):
> def __hash__(self):
> return 0
This will suck for performance if you put a lot of lists in the same
dictionary. Faster is:
class FastHashableList(list):
def __hash__(self):
return id(self)
> I think python is broken here-- why aren't lists hashable, or why isn't
> there a straightforward way to make memoised() work?
There isn't a straightforward way to make memoised work because -
well, it's not a straightforward thing to make work.
For instance, consider the two hashable list implementations
above. Consider this:
@memoised
def broken(l):
return len(l) + 1
x = HL([1, 2, 3]) # Or FHL
print broken(x)
x.append(4)
print broken(x)
Will your memoised handle this case correctly?
Which is also why lists aren't hashable - there's no good definition
of the hash of a list that isn't broken for some common use case.
<mike
--
Mike Meyer <mwm at mired.org> http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
More information about the Python-list
mailing list