Title: Set == non-Set is a TypeError
Type: Stage:
Components: Library (Lib) Versions: Python 2.3
Status: closed Resolution: fixed
Dependencies: Superseder:
Assigned To: tim.peters Nosy List: creedy, gvanrossum, rhettinger, tim.peters
Priority: normal Keywords:

Created on 2003-02-25 19:37 by creedy, last changed 2003-03-02 00:32 by tim.peters. This issue is now closed.

File name Uploaded Description Edit
test_sets.diff rhettinger, 2003-03-01 17:51 New tests
Messages (6)
msg14833 - (view) Author: Chris Reedy (creedy) Date: 2003-02-25 19:37
Comparing Sets to non-Sets results in a TypeError. For

>>> from sets import Set
>>> x = Set([1])
>>> x == 2
TypeError: Binary operation only permitted between sets

This seems to be inconsistent  with other Python
behavior. For example:

>>> (1,2,3) == 2
>>> "abcd" == 2

Assuming that the standard behavior is what is desired,
the implementation of __eq__ and other comparison
operators in should be changed to return
NotImplemented when the other object is not a Set.

Note: Looking at the code, I'm not sure whether the
implementation of __lt__, __le__, etc. should also be
changed to not return a Type Error.
msg14834 - (view) Author: Raymond Hettinger (rhettinger) * (Python committer) Date: 2003-03-01 02:08
Logged In: YES 

The OP added this note at the behest of 
comp.lang.python.  The thread is at: and includes
some comments by Tim.

Assigning to Guido to decide whether he wants to keep 
that behavior.
msg14835 - (view) Author: Tim Peters (tim.peters) * (Python committer) Date: 2003-03-01 02:45
Logged In: YES 

Short course: returning NotImplemented (== falling back to 
address comparison, unless the other comparand wants  to 
handle it) instead for __eq__ and __ne__ would be fine.  
That would be similar to what was done for datetime 
objects in 2.3a2.  The other 4 relationals shouldn't be 
msg14836 - (view) Author: Guido van Rossum (gvanrossum) * (Python committer) Date: 2003-03-01 02:48
Logged In: YES 

Yes, that's the right solution. In general, more objects
should implement this behavior: __eq__, __ne__ return
NotImplemented, the others continue to raise TypeError.
msg14837 - (view) Author: Raymond Hettinger (rhettinger) * (Python committer) Date: 2003-03-01 18:02
Logged In: YES 

That makes sense.  What I don't understand is how to 
implement it.  Any change I make to __eq__ and __ne__ 
causes test_cmp to fail.

The new tests are attached.
msg14838 - (view) Author: Tim Peters (tim.peters) * (Python committer) Date: 2003-03-02 00:32
Logged In: YES 

This turned out to be messier than I hoped, because Set 
also implements __cmp__, so returning NotImplented 
didn't do a lick of good.  See the checkin msg and new code 
comments for discussions of subtleties.

Lib/; new revision: 1.43
Checking in Lib/test/; new revision: 1.21 
Misc/NEWS; new revision: 1.685
Date User Action Args
2003-02-25 19:37:45creedycreate