FW: Set and {} comparison confusion

Alex Martelli aleaxit at yahoo.com
Thu Sep 9 06:48:54 EDT 2004


Roman Yakovenko <roman.yakovenko at actimize.com> wrote:
   ...
> classes have __eq__, __ne__. Classes are mutable - I can't define 
> __hash__ function. __lt__ - I can implement but it will be meaningless.

As long as it respects the fundamental semantics constraints such as:
    a < b and b < c   imply   a < c
    a < b implies not (a == b)
    a < b implies (a != b)
    not (a < a) for any a
and so on, your __lt__will not be 'meaningless' but very useful.

Basically, __lt__ is meaningful if it's transitive, non-reflective, and
compatible with your == and != (which I assume are compatible with each
other); a transitive non-reflective < defines implicitly an equivalence
relation, a eqv b <--> not (a < b or b < a), and you need your == to
express exactly that equivalence relation... so if your == is
meaningful, your < can't really be 'meaningless'!-)

> Thank you for help. I think I have a dicision:
> 1. I will implement meaningless __lt__
> 2. I will sort ( I don't have duplicated items ) every time I need to compare
> 2.1 Because sort is happen in place next time it will take less time to sort.

Yes, that does seem to make sense to me.  Once two lists without
duplicates are sorted, they're equal as sets iff they're == as lists;
and yes, maintaining sorted order is typically quite cheap in Python due
to Tim Peters' powerful natural mergesort algorithm as implemented
inside list.sort (though it might be worth having a look at the bisect
module, it's likely going to be faster to just sort the lists each
time).


> Again - Thanks for help. It was very usefull. It seems that I had wrong
expectation
> from set - " unordered set collection based only on comparison operators".
> My mistake. 

Ah, isn't set documented to need hashable elements?  It should be.  Of
course, _why_ your class appears to be hashable when it defines __eq__
and not __hash__ I dunno -- Python should diagnose that, but it does't
appear to...


Alex



More information about the Python-list mailing list