Repository navigation
"unhashable type" is a beginner-unfriendly error message #132825
Description
Activity
- addedtype-featureA feature request or enhancementA feature request or enhancement
on Apr 23, 2025 StanFromIreland commented
on Apr 23, 2025 on Apr 23, 2025 · Hidden as resolvedshow commentMore actionsI like your proposal. I wrote #132828 to implement your suggested error messages.
Examples:
>>> s=set(); s.add({}) TypeError: Cannot use 'dict' as a set element (unhashable type: 'dict') >>> d = {}; l = [1, 2, 3]; d[l] = 12 TypeError: Cannot use 'list' as a dict key (unhashable type: 'list')
I don't see any way to improve the message.
@cfbolz proposes the change the error message. Currently, the error message is not helpful:
>>> s=set(); s.add({}) TypeError: unhashable type: 'dict' >>> d = {}; l = [1, 2, 3]; d[l] = 12 TypeError: unhashable type: 'list'StanFromIreland commented
on Apr 23, 2025 on Apr 23, 2025 · Hidden as resolvedshow commentMore actionsTypeError: Cannot use 'list' as a dict key (unhashable type: 'list')
Maybe, exception message should starts with lowercase?
It seems other exceptions start with "cannot...".Reacted by Victor Stinner@vstinner thanks a lot Victor, this makes me super happy!
Reacted by Victor Stinner and Daniel Hollas- added a commit that references this issue
on Apr 23, 2025 - added a commit that references this issue
on Apr 23, 2025 What about cases where the key is nested:
{(1, 2, []): ""}?The problem is not the tuple type, but the list type within. The error message would be false if it said that
tuplecannot be used as a dict key. It would also be misleading if it said thatlistcannot be used a dict key, since the user did not use the list directly as a key.What about cases where the key is nested: {(1, 2, []): ""}?
You get this error message:
>>> {(1, 2, []): ""} TypeError: cannot use 'tuple' as a dict key (unhashable type: 'list')@hugovk This one could be added to What’s new section about improved error messages
Reacted by Hugo van KemenadePR welcome :)
OK #133622
Reacted by Hugo van Kemenade- added a commit that references this issue
on Jan 7, 2026 - added a commit that references this issue
on Mar 2, 2026 - added a commit that references this issue
on Mar 2, 2026
Feature or enhancement
Proposal:
Every time I'm teaching dicts and sets to beginners, someone tries to use lists or other mutable data structures as dict keys or set members. The error message in that case is unhelpful, because it describes the problem in very technical terms (when you're just starting you have no idea what a hash function is). it could be changed to also add what operation is impossible as a result:
That way, the problem is stated much more in terms of what the programmer is actually trying to do.
Has this already been discussed elsewhere?
No response given
Links to previous discussion of this feature:
No response
Linked PRs