Why is dictionary.keys() a list and not a set?

"Martin v. Löwis" martin at v.loewis.de
Sat Nov 26 17:03:24 EST 2005


Christoph Zwerschke wrote:
>> This is not true. The second definition of __hash__ does not meet
>> the specifications:
>> "The only required property is that objects which compare equal have the
>> same hash value"
> 
> 
> As Mike has written in his last posting, you could easily "fix" that by 
> tweaking the equality relation as well. So technically speaking, Mike is 
> probably right.

No. If you define both __hash__ and __eq__ consistently, then __hash__
would meet the specification. As posted in the example, __hash__ does
not meet the specification, contrary to Mike's claim that it does.

> It would completely break common-sense semantics, 
> because for mylist2, if I have a=[1] and b=[1] then I will have a!=b. 
> This would not be very reasonable, but probably allowed by Python.

If you have a=[1] and b=[1], then *always* a==b; you cannot
change the semantics of list displays. To achieve !=, you
would need to have a=mylist2([1]), b=mylist([2]). Whether or not
it is common sense that classes named "mylist2" compare equal
if they consist of the same items, I don't know - I personally don't
have any intuition as to what a class named "mylist2" should or
should not do.

Just that it has "list" in its name provides not sufficient clue: for
example, IdentityDictionary has "dictionary" in its name, yet I would
*not* expect that equality is used to compare keys, but instead I
would expect that identity is used.

Regards,
Martin



More information about the Python-list mailing list