[New-bugs-announce] [issue41114] "TypeError: unhashable type" could often be more clear

Samuel Freilich report at bugs.python.org
Thu Jun 25 08:48:17 EDT 2020


New submission from Samuel Freilich <sfreilich at google.com>:

Currently, if you (for example) put a dict as a value in a set or key in a dict, you get:

TypeError: unhashable type: 'dict'

I'm pretty sure this wording goes back a long time, but I've noticed that Python beginners tend to find this really confusing. It fits into a pattern of error messages where you have to explain why the error message is worded the way it is after you explain why the error message occurs at all. There are many instances of:
https://stackoverflow.com/questions/13264511/typeerror-unhashable-type-dict

It would be clearer if the message was something like:

TypeError: 'dict' can not be used as a set value because it is an unhashable type.

(Or "dict key" instead of "set value".)

The exception is raised in PyObject_Hash, so that doesn't have some of the context about how/why hash was called. That's called in a lot of places.

Possibly, PyObject_Hash and PyObject_HashNotImplemented could take the format string passed to PyErr_Format as an optional second argument, defaulting to the current behavior? Then certain callers (in particular, the set and dict constructor, set and dict methods that add set values or add/modify dict keys) could provide clearer error messages.

----------
messages: 372366
nosy: sfreilich
priority: normal
severity: normal
status: open
title: "TypeError: unhashable type" could often be more clear
type: behavior

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue41114>
_______________________________________


More information about the New-bugs-announce mailing list