On Sat, Jun 22, 2013 at 11:15 AM, Rick Johnson
<rantingrickjohn...@gmail.com> wrote:
>     # Literal
>     py> d = {[1]:2}
>     Traceback (most recent call last):
>       File "<pyshell#0>", line 1, in <module>
>         d = {[1]:2}
>     TypeError: unhashable type: 'list'
>     # Symbol
>     py> lst = [1]
>     py> d = {lst:2}
>     Traceback (most recent call last):
>       File "<pyshell#2>", line 1, in <module>
>         d = {lst:2}
>     TypeError: unhashable type: 'list'
>
> Hmm, maybe only certain mutables work? Great, more esoteric
> rules! Feel free to enlighten me since i'm not going to
> waste one second of my time pursuing the docs just to learn
> about ANOTHER unintuitive PyWart i have no use for.

>>> class HashableList(list):
        def __hash__(self):
                return 42

>>> a=HashableList()
>>> a
[]
>>> a.append(1)
>>> a.append(2)
>>> a.append(3)
>>> a
[1, 2, 3]
>>> d={a:123}
>>> d
{[1, 2, 3]: 123}
>>> a.append(4)
>>> d[a]
123

It's nothing to do with mutability, all to do with hashability. And
you can pick a number of different ways of hashing these objects, like
going for the object's id(), or attempting to hash tuple(self) and
falling back on id(), or anything you like. Easy.

ChrisA
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to