[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.python

Re: Constraints on __sub__, __eq__, etc.

Roald de Vries

2/19/2010 10:31:00 AM

On Feb 18, 2010, at 5:28 PM, Stephen Hansen wrote:
> On Thu, Feb 18, 2010 at 8:19 AM, Andrey Fedorov
> <anfedorov@gmail.com>wrote:
>> It seems intuitive to me that the magic methods for overriding the
>> +, -, <, ==, >, etc. operators should have no sideffects on their
>> operands. Also, that == should be commutative and transitive, that
>> > and < should be transitive, and anti-commutative.
>>
>> Is this intuition written up in a PEP, or assumed to follow from
>> the mathematical meanings?
>
> It may be intuitive to you, but its not true, written down anywhere,
> nor assumed by the language, and the mathematical meaning of the
> operators doesn't matter to Python. Python purposefully does not
> enforce anything for these methods.

Still, it's clear that (for example) '==' is not just a normal
function call. Look at this example (in ipython):

>>> False == False == False
True
>>> True == False == False
False
>>> (True == False) == False
True

Anybody knows how why this is so?



1 Answer

Peter Otten

2/19/2010 11:30:00 AM

0

Roald de Vries wrote:

> On Feb 18, 2010, at 5:28 PM, Stephen Hansen wrote:
>> On Thu, Feb 18, 2010 at 8:19 AM, Andrey Fedorov
>> <anfedorov@gmail.com>wrote:
>>> It seems intuitive to me that the magic methods for overriding the
>>> +, -, <, ==, >, etc. operators should have no sideffects on their
>>> operands. Also, that == should be commutative and transitive, that
>>> > and < should be transitive, and anti-commutative.
>>>
>>> Is this intuition written up in a PEP, or assumed to follow from
>>> the mathematical meanings?
>>
>> It may be intuitive to you, but its not true, written down anywhere,
>> nor assumed by the language, and the mathematical meaning of the
>> operators doesn't matter to Python. Python purposefully does not
>> enforce anything for these methods.
>
> Still, it's clear that (for example) '==' is not just a normal
> function call. Look at this example (in ipython):
>
> >>> False == False == False
> True
> >>> True == False == False
> False
> >>> (True == False) == False
> True
>
> Anybody knows how why this is so?

As Chris said

expr1 <op1> expr2 <op2> expr3 <op3> ...

is resolved as

(expr1 <op1> expr2) and (expr2 <op2> expr3) and (expr3 <op3> ...

where each exprN is evaluated just once.


For this to become the obvious way you have to look at interval checks like

a < b < c

Peter