Rich Comparisons Gotcha

Terry Reedy tjreedy at udel.edu
Mon Dec 8 20:02:38 EST 2008


Robert Kern wrote:
> Terry Reedy wrote:
>> Rasmus Fogh wrote:
> 
>>> 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.
> 
> No, it's actually required.
> 
> In [4]: class A(object):
>     def __contains__(self, other):
>         return 'foo'
>    ...:
>    ...:
> 
> In [7]: a = A()
> 
> In [8]: 1 in a
> Out[8]: True
> 
> 
> Okay, so it will coerce to True/False for you, but unlike rich 
> comparisons, the return value must be interpretable as a boolean.

Interesting.  I did not expect that from "Should return true if item is 
in self, false otherwise.", but maybe the lowercase true/false is an 
(undocumented?) abbreviation for 'object with Boolean value True/False'.

Of course, if the return value is not so interpretable, or if 
__contains__ raises an exception, there is no coercion and the OP's code 
will not work.

A different summary of my main point in this thread: Dynamic binding and 
special method hooks make somewhat generic code possible, but the same 
special method hooks make absolutely generic code nearly impossible.

tjr





More information about the Python-list mailing list