Why is dictionary.keys() a list and not a set?
Christoph Zwerschke
cito at online.de
Sun Nov 27 03:44:17 EST 2005
Martin v. Löwis schrieb:
>> 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.
Ok, the example was incomplete, but in principle, this could be fixed by
adding a tweaked __eq__ method. So for completeness sake:
class mylist2(list):
def __hash__(self): return id(self)
def __eq__(self, other): return self is other
def __ne__(self, other): return self is not other
list = mylist2
a = list([1])
b = list([1])
print a, b, a == b, a != b
> If you have a=[1] and b=[1], then *always* a==b; you cannot
> change the semantics of list displays.
Surely, since you can't change the methods of built-in types. But you
can create your own local list displays with a tweaked semantics as in
the above example.
Anyway, the original question was: Are mylist1 and mylist2 (as above) to
be considered "hashable" types or not? I think "technically" speaking,
they are, and the "technical" definition is the only one that counts.
-- Christoph
More information about the Python-list
mailing list