Reputation: 1027
I have the following:
I see the following object has __hash__
attribute
a=[1,2,3]
>>> dir(a)
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delsli
ce__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getit
em__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__',
'__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__r
educe__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__'
, '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'a
ppend', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort'
]
>>> dict1={a:'55'}
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
Q:even though it has __hash__
attribute, still it cannot be used as key.Why?
Upvotes: 0
Views: 209
Reputation: 251363
Did you try looking at the value of the attribute?
>>> print(a.__hash__)
None
Just because something has a __hash__
attribute doesn't mean it's hashable; the __hash__
attribute has to be a callable that actually hashes it (instead of, e.g., raising an exception).
Upvotes: 3