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

"Martin v. Löwis" martin at v.loewis.de
Sat Nov 26 18:59:09 EST 2005


Mike Meyer wrote:
>>This is not true. The second definition of __hash__ does not meet
>>the specifications:
> 
> 
> The specification isn't on the __hash__ method, but on objects.

What does it mean for a specification to be "on" something? The
specification I quoted is listed "under" the __hash__ heading
of the reference manual.

> Instances of mylist2 that aren't otherwise tweaked won't meet the
> specification.

Right, that's what I meant.

> That's pretty flaky. The same docs say:
> 
> Should return a 32-bit integer usable as a hash value for dictionary
> operations.

What is flaky about this?

> the dictionary implementation requires that a key's hash value is
> immutable

Indeed, the question here is: what does "an object is immutable"
mean in this context? You appear to read it as "an object whose
state does not change", however, what it really means is "an object
which will always use the same state in __hash__ and __eq__".

> Maybe those are only "recommended" properties, but any class that
> doesn't meet them is going to have instances with interesting
> behaviors in sets and as dictionary keys.

Indeed, you can anything return you want in __hash__, or always
raise an exception. What precisely the result of dictionary
operations is when you do so is undefined in Python.

> That's a problem with mylist2 instances, and may or may not be a
> problem in the mylist2 __hash__ method. You can't tell just by
> examining the __hash__ method whether or not it meets this
> specification.

Correct. I would expect that this is the case for any specification
of __hash__ you can come up with: __hash__ would typically refer
to the state of the object, and whether or not the results meets
some specified requirement would also depend on what the state is.
(unless either the specification is trivial (e.g. "may or may
not return a value") or the implementation is trivial (e.g.
"return 0"))

Regards,
Martin



More information about the Python-list mailing list