Ordering python sets

Arnaud Delobelle arnodel at googlemail.com
Wed Nov 5 16:03:05 EST 2008


Mr.SpOOn <mr.spoon21 at gmail.com> writes:

> The discussion's gone a bit off topic so I don't know if it is a good
> idea to continue here. I'll try.
>
> My first question was about a way to order a python set. Someone
> suggested to try this module:
>
> http://code.activestate.com/recipes/528878/
>
> It seemed pretty good, but I've tried it just today and something
> doesn't work.  I think it doesn't work because what I have to order
> are objects and not just numbers. Anyway, I'm not sure that this is
> the problem.
>
> What I get when I try to append one of my object is:
>
>   File "notes.py", line 245, in __init__
>     self.append(root)
>   File "ordered_set.py", line 78, in append
>     self._insertatnode(self._end.prev, element)
>   File "ordered_set.py", line 110, in _insertatnode
>     if element in self._map:
> TypeError: unhashable instance
>
> Don't know if it is important, but inside the class of the object that
> I'm trying to append, I redefined the __eq__ and __gt__ method.

Only hashable objects can go in a set.  By default a class you define is
not hashable (unless it descends from a hashable class).  To remedy this
you can define a __hash__ method in your class.  IIRC the only
requirement of a hash function is that two equal objects have the same
hash.

HTH

-- 
Arnaud



More information about the Python-list mailing list