Python List of Unique Items
Problem
You’ve tried to add an object into a set and a TypeError: unhashable type:
exception was raised. You were probably using a set because you needed a collection of objects without duplicates. If that was the case, two ways of solving this come to mind:
-
Implement the
__hash__
method for the parent class of that object as per the guidelines in the Python documentation. -
Extend the inbuilt data-type
list
and override it’sappend()
method:An instance of this class will behave exactly like a normal list, but won’t allow duplicates to be added to it.
Note: The
item
object’s parent class needs to have it’s__eq__
method implemented for this to work.