How to check something is in a list with rich-comparison objects?

Steven D'Aprano steven at REMOVE.THIS.cybersource.com.au
Wed Sep 16 03:23:28 EDT 2009


On Wed, 16 Sep 2009 03:57:30 -0300, Gabriel Genellina wrote:

> En Wed, 16 Sep 2009 03:36:32 -0300, Jason <jason.heeris at gmail.com>
> escribió:
> 
>> On Sep 16, 2:39 am, "Gabriel Genellina" <gagsl-... at yahoo.com.ar> wrote:
>>> Looks like a bug in pysvn. Some class (whatever
>>> pysvn.wc_notify_action.status_completed is) is not well written. When
>>> compared against something unknown, it should return NotImplemented
>>> instead of raising AttributeError.
> 
> (top posting corrected)
> 
>> I will raise this with pysvn, if I can ever find their issue reporting
>> system.
>>
>> In the meantime, I suppose I can only do this by traversing the list
>> with a loop and catching exceptions. Ugly, but seems to be the only
>> way.
> 
> You might use a list subclass and override its __contains__ method (and
> perhaps index() too). It's the same ugly code, but at least expressions
> like:
> 
> 'foo' in some_list
> 
> would still work.


Or you can wrap each item in an object that does the right thing.

# untested
class Wrapper:
    # Thin wrapper to make equals comparisons work correctly
    def __init__(self, payload):
        self.payload = payload
    def __eq__(self, other):
        payload = self.payload
        try:
            return payload.__eq__(other)
        except AttributeError:
            return other.__eq__(payload)

some_list = map(Wrapper, some_list)



-- 
Steven



More information about the Python-list mailing list