Constraints on __sub__, __eq__, etc.
Andrey Fedorov
anfedorov at gmail.com
Thu Feb 18 17:32:17 CET 2010
>
> 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.shansen at gmail.com>wrote:
> On Thu, Feb 18, 2010 at 8:19 AM, Andrey Fedorov <anfedorov at 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
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20100218/0fe6d793/attachment.html>
More information about the Python-list
mailing list