You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Show which tuple item is unhashable when a nested dict key or set element is rejected #161433
TypeError: cannot use 'tuple' as a dict key (unhashable type: 'list')
Tuples are normally valid keys, so the message appears to reject the tuple because
of a list that isn't visibly related to it. Nothing says that the list is inside
the tuple, or where. This was pointed out on gh-132825 and again in the PEP 814
thread, and it is harder to follow with deeper nesting or longer tuples.
I'd suggest adding a note in the error path of tuple_hash, following what the json module already does for nested values:
>>> json.dumps({"a": [1, object()]})
TypeError: Object of type object is not JSON serializable
when serializing list item 1
when serializing dict item 'a'
>>> hash(("alice", ["a", "b"])) # proposed
TypeError: unhashable type: 'list'
when hashing tuple item 1
The note would be added only after an item's hash has failed, so successful hashing
is unaffected. Nested tuples would produce one note per level.
Dependency on gh-149313: the dict and set paths currently replace the exception
and discard its notes, so the note would only become visible for dict keys and set
elements once that issue is fixed. Until then, only direct hash() calls would
show it.
Reproduced on 3.14.6 and 3.15.0b2.
I noticed this behavior and found it confusing myself, and the proposal is my own. I used Claude to help write this up in English and to re-check the behavior.
Has this already been discussed elsewhere?
This is a minor feature, which does not need previous discussion elsewhere
Activity
pythongh-161433: Add tuple item context to hash TypeError
pythongh-161433: Test tuple hashing exception notes
pythongh-161433: Add NEWS entry and correct CI workflow formatting
pythongh-161433: Add tuple item context to hashing errors
pythongh-161433: Consolidate tuple hashing note tests
pythongh-161433: Acknowledge original issue author WakaTaira