insert unique data in a list

mattia gervaz at gmail.com
Mon Dec 14 12:13:24 EST 2009


Il Sun, 13 Dec 2009 21:17:28 -0800, knifenomad ha scritto:

> On 12월14일, 오후12시42분, Steven D'Aprano
> <ste... at REMOVE.THIS.cybersource.com.au> wrote:
>> On Sun, 13 Dec 2009 17:19:17 -0800, knifenomad wrote:
>> > this makes the set type hashable.
>>
>> > class Set(set):
>> >     __hash__ = lambda self: id(self)
>>
>> That's a *seriously* broken hash function.
>>
>> >>> key = "voila"
>> >>> d = { Set(key): 1 }
>> >>> d
>>
>> {Set(['i', 'a', 'l', 'o', 'v']): 1}>>> d[ Set(key) ]
>>
>> Traceback (most recent call last):
>>   File "<stdin>", line 1, in <module>
>> KeyError: Set(['i', 'a', 'l', 'o', 'v'])
>>
>> --
>> Steven
> 
> of course it is broken as long as it uses it's instance id. i added this
> to notify that unhashable can become hashable implementing __hash__
> inside the class. which probably set to None by default.

Ok, nice example, but I believe that using id() as the hash function can 
lead to unexpected collisions.



More information about the Python-list mailing list