Rich Comparisons Gotcha
Robert Kern
robert.kern at gmail.com
Mon Dec 8 17:13:12 EST 2008
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.
--
Robert Kern
"I have come to believe that the whole world is an enigma, a harmless enigma
that is made terrible by our own mad attempt to interpret it as though it had
an underlying truth."
-- Umberto Eco
More information about the Python-list
mailing list