Rich Comparisons Gotcha

MRAB google at mrabarnett.plus.com
Mon Dec 8 17:56:31 EST 2008


Terry Reedy wrote:
> Rasmus Fogh wrote:
> 
>> For my personal problem I could indeed wrap all objects in a wrapper with
>> whatever 'correct' behaviour I want (thanks, TJR). It does seem a bit
> 
> I was not suggesting that you wrap *everything*, merely an adaptor for 
> numpy arrays in whatever subclass and source it is that feeds them to 
> your code.  It is fairly unusual, I think, to find numpy arrays 'in the 
> wild', outside the constrained context of numerical code where the 
> programmer uses them intentionally and hopefully understands their 
> peculiarities.
> 
>> much, though, just to get code like this to work as intended:
>>   alist.append(x)
>>   print ('x is present: ', x in alist)
> 
> Even if rich comparisons as you propose, the above would *still* not 
> necessarily work.  Collection classes can define a __contains__ that 
> overrides the default and that can do anything, though True/False is 
> recommended.
> 
If you have a list of results and you want to see whether one of them is 
Nan then the obvious way is "Nan in results", but __contains__ uses 
__eq__ and Nan == Nan returns False, so "Nan in results" returns False. 
Hmm... "Nan is Nan" returns True, so if there was a version of 
__contains__ which used "is" then "Nan in results" would return True. 
Perhaps "Nan is in results"? Or would that be too confusing, ie "in" vs 
"is in"?

> As best I can think of at the moment, the only things you can absolutely 
> depend on is that builtin id(ob) will return an int, that 'ob1 is ob2' 
> (based in id()) will be True or False, and that builtin type(ob) will be 
> a class (at least in 3.0, not sure of 2.x).  The names can be rebound 
> but you can control that within the module you write.
> 
I wonder whether there could be some syntactic sugar which would wrap 
try...except... around an expression, eg "except(foo(), False)", which 
would return False if foo() raised an exception, otherwise return the 
result of foo().

> This is what I meant when I said that 'generic' nearly always needs to 
> be qualified to something like 'generic for objects that meet the 
> interface requirements'.  Every function has that precondition as part 
> of its implied contract.  Your code has an interface requirement that 'x 
> in y' not raise an exception.  An x,y pair that does it outside its 
> contract.
> 



More information about the Python-list mailing list