[ZODB-Dev] Comparing BTrees.IOBTree.IOSet(s)

Tim Peters tim at zope.com
Sun Nov 2 16:06:13 EST 2003


[Simon Pamies]
> how can I compare two IOSets?

Well, first you'd have define what comparing two IOSets means, because
there's no compelling total ordering on sets.  You'll have to make up some
more-or-less arbitrary meaning.

> a = IOSet().update([1,2,3,4])
> b = IOSet().update([1,2,3,4])
> a == b
> 0

Like instances of a Python class that doesn't implement __cmp__, IOSets now
are compared by object identity ("memory address").  That's one arbitrary
total ordering, where s1 == s2 if and only if id(s1) == id(s2).  All the
BTree-based data types behave this way now.

> I can use difference(a,b) but I do not understand
> why the __cmp__ method isn't overwritten.

You'd have to ask Jim why he didn't spend time making up some other
arbitrary total ordering, but I think the "spend time" part of the question
supplies the answer <wink>.

Maybe cmp(tuple(a), tuple(b)) gives you a total ordering you'd be happier
with (in particular, it calls IOSets a and b equal if and only if the IOSets
contain equal elements (where "equal elements" is defined by how elements
choose to compare themselves)).

The Set type in Python 2.3 exploits "rich comparisons" to provide a partial
ordering on sets, using set containment as the fundamental relation:

>>> from sets import Set
>>> Set([1, 2, 3]) == Set([1, 2, 3])  # equal elements?
True
>>> Set([1, 2]) < Set([1, 2, 3])  # first set proper subset of second?
True
>>> Set([1, 2, 3]) < Set([1, 2, 3]) # ditto
False
>>> a, b = Set([1, 3]), Set([1, 2])
>>> a < b
False
>>> a == b
False
>>> a > b  # trichotomy doesn't hold -- it's a partial ordering
False
>>> cmp(a, b)
Traceback (most recent call last):
  File "<pyshell#12>", line 1, in -toplevel-
    cmp(a, b)
  File "C:\PYTHON23\Lib\sets.py", line 128, in __cmp__
    raise TypeError, "can't compare sets using cmp()"
TypeError: can't compare sets using cmp()
>>>




More information about the ZODB-Dev mailing list