The documentation for dictionaries says "A dictionary's keys are
almost arbitrary values. Only values containing lists, dictionaries or
other mutable types (that are compared by value rather than by
object identity) may not be used as keys." This is wrong. tuples are
an immutable type, but not all tuples can be used as keys.
The set documentation says "A set object is an unordered collection
of immutable values.". This is also wrong - at least for common
definitions of immutable.
Immutability is a convenient way of dealing with builtin types, but is
a red herring. It's whether or not the object has a hash value that
matters, and it's the behavior of that hash value (coupled with
comparison) that determine whether or not things behave as
expected.
The __hash__ documentation deals with these issues. I suggest
replacing the current descriptions with one that references hashing,
and a footnote pointing to the __hash__ docs for details:
Any hashable object(1) can be used as a dictionary key/set element.
Lists, sets and dicts are not hashable, and can not be used. Tuples
can be used if all the things they contain are hashable. Instances of
all other built-in types and most user-defined classes are hashable.
(1) Objects for which the hash() function returns an appropriate
value. See the __hash__ documentation for details.
|