python / cpython

The Python programming language
https://www.python.org
Other
63.19k stars 30.26k forks source link

Tutorial: mutable objects may be keys #39089

Closed 602e5655-9e0a-43fb-866b-c4d2cb5e05da closed 21 years ago

602e5655-9e0a-43fb-866b-c4d2cb5e05da commented 21 years ago
BPO 791397
Nosy @rhettinger

Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.

Show more details

GitHub fields: ```python assignee = None closed_at = created_at = labels = ['docs'] title = 'Tutorial: mutable objects may be keys' updated_at = user = 'https://bugs.python.org/brianhv' ``` bugs.python.org fields: ```python activity = actor = 'mcherm' assignee = 'none' closed = True closed_date = None closer = None components = ['Documentation'] creation = creator = 'brianhv' dependencies = [] files = [] hgrepos = [] issue_num = 791397 keywords = [] message_count = 3.0 messages = ['17838', '17839', '17840'] nosy_count = 3.0 nosy_names = ['mcherm', 'rhettinger', 'brianhv'] pr_nums = [] priority = 'normal' resolution = 'wont fix' stage = None status = 'closed' superseder = None type = None url = 'https://bugs.python.org/issue791397' versions = [] ```

602e5655-9e0a-43fb-866b-c4d2cb5e05da commented 21 years ago

http://python.org/doc/tut/node7.html#SECTION007400000000000000000

The tutorial section 5.4 ("Dictionaries") says, "Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys." This strongly implies that only immutable objects may be keys, and I always assumed that to be the case. I have recently learned that is not true.

I would suggest a change along the lines of "which can be any immutable type or mutuable types under some circumstances," with a link to further elaboration on what is required for a type to be hashable.

rhettinger commented 21 years ago

Logged In: YES user_id=80475

I prefer the current wording which shifts you away perilous paths. It is possible to create a hashable, mutable class, but you had better know what you're doing if you want to use the objects as dictionary keys and expect to be able to retrieve them later

0feaae82-67a9-4bac-ad01-3319eddb59c0 commented 21 years ago

Logged In: YES user_id=99874

I'm with Raymond on this: the tutorial is intended for beginners, and I'm very happy to have beginners believe that only immutable objects can be keys. IMHO (which could easily be wrong in this case), more advanced users will realize that the existance of __hash__ makes it POSSIBLE to make mutables hashable, although they may well need additional documentation to figure out when doing so will work and when it will break things. But this level of detail doesn't belong in the tutorial (perhaps in a FAQ someplace?).