[Tutor] hash value input
Kent Johnson
kent37 at tds.net
Fri Jan 29 19:41:50 CET 2010
On Fri, Jan 29, 2010 at 1:20 PM, Rich Lovely <roadierich at googlemail.com> wrote:
> I've played with this a little. The following class was quite handy for this:
>
> class BrokenHash(object):
> def __init__(self, hashval):
> self.hashval = hashval
> def __hash__(self):
> return self.hashval
>
> It basically implements the python hashable interface, but in a manner
> that is "broken" - it allows you control over what the object points
> to.
>
> From this, we can tell that chaning the value of an object's hash
> changes its "bucket":
>
>>>> b = BrokenHash(1)
>>>> d = {b:1}
>>>> b.hashval=2
>>>> d[b]
> Traceback (most recent call last):
> File "<stdin>", line 1, in <module>
> KeyError: <__main__.BrokenHash object at 0x657d70>
>
> But it's more than just the objects hash:
>
>>>> b2 = BrokenHash(hash("foo"))
>>>> hash(b2) == hash("foo")
> True
>>>> d2 = {b2: "bar", "foo": "baz"}
>>>> print d2
> {<__main__.BrokenHash object at 0x657e10>: 'bar', 'foo': 'baz'}
>
> (If they both fell into the same bucket, d2['foo'] would overwrite d2[b2]
Only if they compared equal. Placement and retrieval of items in hash
tables depends on both the hash value and equality comparisons. The
hash value determines the bucket, equality is used to disambiguate
keys with the same hash value.
> It appears to be some combination of identity and hash. It is not,
> however, dependant on type:
>
>>>> b3 = BrokenHash(hash("foo")) #same hash as b2
Same hash but not equal.
Kent
>>>> d2[b3]
> Traceback (most recent call last):
> File "<stdin>", line 1, in <module>
> KeyError: <__main__.BrokenHash object at 0x657e90>
>
> Don't know if that's helped at all.
>
> --
> Rich "Roadie Rich" Lovely
More information about the Tutor
mailing list