__eq__ and sets

Gareth McCaughan Gareth.McCaughan at pobox.com
Tue Feb 25 18:12:51 EST 2003


Tim Peters wrote:

[Chris Reedy reported:]
> >  >>> from sets import Set
> >  >>> x = Set([1])
> >  >>> x == 2
> > TypeError: Binary operation only permitted between sets
...
>  It's the implemented behavior <wink>.
>
> > In the case in question, I was expecting false to be returned. Changing
> > the __eq__ and __ne__ operators in sets.py to return NotImplemented
> > instead or raising an exception would result in the behavior I was
> > expecting.
>
> No, it wouldn't.  If, when you compare x to y, both objects return
> NotImplemented, Python automatically falls back to comparing x and y by
> their memory addresses (cmp(id(x), id(y))).  The Set class definitely didn't
> want you to get a nonsense result from "x == 2", and, in the absence of a
> meaningful result, the only way to stop the comparison machinery from
> falling back to address comparison is to raise an exception.

In what sense would comparing addresses give a nonsense result here?
If x is a Set and y is not a Set, then (1) it will fall back to
comparing addresses, (2) that will say that they're not equal,
and (3) that's what you want in general. If y is of some funny
type that wants to compare equal to certain Sets, then it's up
to the implementors of that type to make it happen by not returning
NotImplemented.

Presumably I'm missing something. What?

-- 
Gareth McCaughan  Gareth.McCaughan at pobox.com
.sig under construc




More information about the Python-list mailing list