[Python-Dev] dict __contains__ raises TypeError on unhashable input

Antoine Pitrou solipsis at pitrou.net
Sat Jul 20 12:21:41 CEST 2013


On Fri, 19 Jul 2013 16:47:36 -0700
Ethan Furman <ethan at stoneleaf.us> wrote:
> While working on issue #18508 I stumbled across this:
> 
> Traceback (most recent call last):
> ...
>    File "/usr/local/lib/python3.4/enum.py", line 417, in __new__
>      if value in cls._value2member_map:
> TypeError: unhashable type: 'list'
> 
> I'll wrap it in a try-except block, but I must admit I was surprised the answer wasn't False.  After all, if the input 
> is unhashable then obviously it's not in the dict; furthermore, if I were to compare the number 5 with a set() I would 
> get False, not a TypeMismatch error, and dict keys are basically done by equality, the hash is just (?) a speed-up.

Testing containment of an unhashable key in a dict is a programming
error, so I'd prefer that we keep the TypeError here.

Same reasoning as for:

>>> 5 in "abc"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not int

Sure, 5 technically isn't in "abc" and therefore the "in" operator
could return False, but it's better to highlight the programming error.

Regards

Antoine.




More information about the Python-Dev mailing list