Constraints on __sub__, __eq__, etc.
Stephen Hansen
apt.shansen at gmail.com
Thu Feb 18 17:28:01 CET 2010
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/93c476e6/attachment.html>
More information about the Python-list
mailing list