>
> 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.


Right, so neither is anything in PEP-8, but it's still considered "good
practice". I'm running across examples like you gave (__sub__ having a
side-effect on the left-hand operand) in some code, and am trying to find
concrete justification for avoiding it.

- Andrey

On Thu, Feb 18, 2010 at 11:28 AM, Stephen Hansen <apt.shan...@gmail.com>wrote:

> On Thu, Feb 18, 2010 at 8:19 AM, Andrey Fedorov <anfedo...@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. Consider:
>
> >>> class Test(object):
> ...     def __init__(self, v):
> ...             self.v = v
> ...     def __add__(self, other):
> ...             self.v = self.v + other
> ...             return "Ow!"
> ...
> >>> t = Test(5)
> >>> t + 2
> 'Ow!'
> >>> t.v
> 7
>
> It not only alters an operand, but its not even returning a meaningful
> result. This can be abused, but is also useful for certain uses.
>
> --S
>
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to