Thursday, June 23, 2011

Dict Destroyer!

Let's make a class that returns a random number for its hash.

>>> import random
>>> class DictDestroyer(object):
...    def __hash__(self):  return random.randint(0, 2**31)
>>> d = DictDestroyer()
>>> hash(d)
>>> hash(d)

Now, DictDestroyer lives up to its name:

>>> a = {d:1, d:2, d:3}
>>> import pprint
>>> pprint.pprint(a)
{<__main__.DictDestroyer object at 0x00CE8E90>: 1,
 <__main__.DictDestroyer object at 0x00CE8E90>: 2,
 <__main__.DictDestroyer object at 0x00CE8E90>: 3}

What is this?  One key has multiple values?  What happens when data is fetched?

>>> a[d]
>>> a[d]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: <__main__.DictDestroyer object at 0x00CE8E90>

Inconsistent behavior.  Some times it returns one of the values, other times it gives a key error.
The C source for python dictionaries holds the answer.
I'll have to update later when I figure it out.

No comments:

Post a Comment