__contains__() and overload of in : Bug or Feature ???

Colin J. Williams cjw at sympatico.ca
Sun Sep 23 19:30:56 EDT 2007


sebastien.lannez at gmail.com wrote:
> Thanks for your quick response.
> 
>>> I need to overload the operator in and let him
>>> return an object ... It seems it is not a
>>> behavior Python expect :
>>>
>>>>>> class A:
>>> ...    def __contains__(self,a):
>>> ...        return 'yop'
>>> ...
>>>>>> a=A()
>>>>>> print 'toto' in a
>>> True
>>>>>> print a.__contains__('toto')
>>> yop
> 
>> Not sure what you're trying to achieve,
> 
> Using Python as an algebraic parser for
> symbolic mathematical equation and I need
> that the 'in' operator returns an object based
> on its two arguments.
> 
>> but the semantics of the "in" operator
>> make it return a boolean value.
> 
> That is why I need to overload it.
> 
>> The string "yop" evaluates to the boolean
>> value True, as it is not empty.
> 
> Does it means that when overloading an operator, python just
> wrap the call to the method and keep control of the returned
> values ??? Is there a way to bypass this wrapping ???
> 
Can you not achieve what you wish to do with a conditional
expression?

"yop" if a in b else "nop"

Colin W.




More information about the Python-list mailing list