A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://mail.python.org/pipermail/python-dev/2009-October/093069.html below:

[Python-Dev] nonstandard behavior of reflected functions

[Python-Dev] nonstandard behavior of reflected functionsDarren Dale dsdale24 at gmail.com
Sun Oct 18 16:50:51 CEST 2009
According to http://docs.python.org/reference/datamodel.html , the
reflected operands functions like __radd__ "are only called if the
left operand does not support the corresponding operation and the
operands are of different types. [3] For instance, to evaluate the
expression x - y, where y is an instance of a class that has an
__rsub__() method, y.__rsub__(x) is called if x.__sub__(y) returns
NotImplemented."

Consider the following simple example:

==========================
class Quantity(object):

    def __add__(self, other):
        return '__add__ called'

    def __radd__(self, other):
        return '__radd__ called'

class UnitQuantity(Quantity):

    def __add__(self, other):
        return '__add__ called'

    def __radd__(self, other):
        return '__radd__ called'

print 'Quantity()+Quantity()', Quantity()+Quantity()
print 'UnitQuantity()+UnitQuantity()', UnitQuantity()+UnitQuantity()
print 'UnitQuantity()+Quantity()', UnitQuantity()+Quantity()
print 'Quantity()+UnitQuantity()', Quantity()+UnitQuantity()
==========================

The output should indicate that __add__ was called in all four trials,
but the last trial calls __radd__. Interestingly, if I comment out the
definition of __radd__ in UnitQuantity, then the fourth trial calls
__add__ like it should.

I think this may be an important bug. I'm running Python 2.6.4rc1
(r264rc1:75270, Oct 13 2009, 17:02:06) an ubuntu Karmic. Is it a known
issue, or am I misreading the documentation?

Thanks,
Darren
More information about the Python-Dev mailing list

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4