An unhashable object cannot be inserted into a dict. It is documented, there is good reason for it.
However, I do not understand why it affects a membership test:
if value not in somedict:
print("not present")
I was assuming that a membership test can return only True or False. But when the value is unhashable, it fails with TypeError: unhashable type. I would say True should be the correct answer of this not in test, because the value is clearly not contained in somedict and it is fully irrelevant that it cannot be inserted.
Another example:
try:
result = somedict[value]
except KeyError:
# handle the missing key
When the value is unhashable, it fails with TypeError: unhashable type I would expect the KeyError instead.
Also:
somedict.get(value, default)
does not return the default, but throws the TypeError.
So why unhashable in somedict does not evaluate to False and what is the correct test returning just True or False?
Update:
object.__contains__(self, item)Called to implement membership test operators. Should return true if item is in self, false otherwise.
(from "Data Model - Python Documentation")
Appendix:
This is a simplified part of a user interface program, which failed when one of the arguments was a dict.
# args = list of function arguments created from user's input
# where "V1" stands for value1 and "V2" stands for value2
XLAT = {'V1': value1, 'V2': value2}
args = [XLAT.get(a, a) for a in args]
function(*args)