[Tutor] Implementing sets of user-defined objects

Steven D'Aprano steve at pearwood.info
Fri Jul 23 14:57:56 CEST 2010


On Fri, 23 Jul 2010 09:22:55 pm mhw at doctors.net.uk wrote:
> Dear Tutors,
>
> I am tring to deal with some repeated data, and hence repeated
> objects (I construct objects from the data).
>
> I had hoped to use a set to uniquify the objects. However, I am
> having problems with defining uniqueness.

The objects need to define __eq__ and __hash__, and they must be 
immutable.

The easy way to do so is to inherit from something which is already 
immutable, say strings, ints, tuples or floats:

class MyObject(int):
    """Just like an int, but coloured purple."""
    def __init__(self, *args):
        self.colour = 'purple'


Otherwise, something like this recipe should do the job:

class MyObject(object):
    def __init__(self, a, b):
        self._value = (a, b)  # Private attribute, don't touch this.
    @property
    def value(self):
        return self._value
    def __eq__(self, other):
        if isinstance(other, MyObject): return self.value == other.value
        return NotImplemented  # Let the other object try.
    def __ne__(self, other):
        return not self == other
    def __hash__(self):
        return hash(self.value)
        

If x and y are instances of your class, and x equals y, then hash(x) 
*must* equal hash(y). (The opposite doesn't apply though... if x and y 
hash equal, they don't necessarily have to equal.)



-- 
Steven D'Aprano


More information about the Tutor mailing list