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

Christoph Zwerschke cito at online.de
Fri Nov 25 17:26:25 EST 2005


Mike Meyer wrote:

 > The mutability - or immutability - of an object is irrelevant to
 > the question of whether or not they can be a dictionary key/set
 > element. The critical property is that they are hashable.
 > *Most* immutable builtin types are hashable, and no builtin
 > mutable types are hashable, which deserves a mention.

I think the problem we are facing is that you must distinguish between 
hashable/mutable *types* and hashable/mutable objects. You can have 
*types* like tuple which are hashable/immutable themselves, but can have 
*instances* that are mutable and not hashable, such as ([]).

For the built-in types I think objects are hashable if and only if they 
are immutable (not 100% sure, but can you give a counterexample?). 
That's why I got back to talk about mutability first. But I agree one 
should also explain the problem of non-built-in types.

Maybe one can split the explanation and talk about the built-in 
datatypes first and then explain the situation for user-defined types.

 >>>And the footnote is:
 >>>Instances of Python classes are hashable if they define a __hash__
 >>>method, or if they don't define either __cmp__ or __eq__.
 >>
 >>I think that's not exact enough. For instance, ordinary lists also
 >>define a __hash__ method but are not hashable since that method just
 >>raises an exception.
 >
 > Ordinary lists aren't Python classes.

In your first sentence, it was unclear whether "they" refered to the 
class or the instance. But anyway, what about the following class:

class mylist(list):
     pass

This class definitely has a __hash__ method. But instances of this class 
are not hashable.

-- Christoph



More information about the Python-list mailing list