<blockquote class="gmail_quote" style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0.8ex; border-left-width: 1px; border-left-color: rgb(204, 204, 204); border-left-style: solid; padding-left: 1ex; ">
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.</blockquote>
<div><br></div><div>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.</div>
<div><br></div><div>- Andrey</div><br><div class="gmail_quote">On Thu, Feb 18, 2010 at 11:28 AM, Stephen Hansen <span dir="ltr"><<a href="mailto:apt.shansen@gmail.com">apt.shansen@gmail.com</a>></span> wrote:<br><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">
<div class="im">On Thu, Feb 18, 2010 at 8:19 AM, Andrey Fedorov <span dir="ltr"><<a href="mailto:anfedorov@gmail.com" target="_blank">anfedorov@gmail.com</a>></span> wrote:<br></div><div class="gmail_quote"><div class="im">
<blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex">
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.<div>
<br></div><div>Is this intuition written up in a PEP, or assumed to follow from the mathematical meanings?</div></blockquote><div><br></div></div><div>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:</div>
<div><br></div><div><div>>>> class Test(object):</div><div>... def __init__(self, v):</div><div>... self.v = v</div><div>... def __add__(self, other):</div><div>... self.v = self.v + other</div>
<div>... return "Ow!"</div><div>... </div><div>>>> t = Test(5)</div><div>>>> t + 2</div><div>'Ow!'</div><div>>>> t.v</div><div>7</div><div><br></div></div></div>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.<div>
<br clear="all"><font color="#888888"><div name="mailplane_signature">--S</div></font></div>
</blockquote></div><br>