__coerce__ vs. new-style classes

Hallvard B Furuseth h.b.furuseth at usit.uio.no
Mon Aug 2 17:11:31 EDT 2004


I wrote:

> Without __coerce__, what should __add__(self, other) do if it doesn't
> know how to add the arguments, but the other argument might know how?
> It can't just call other.__radd__(self): That might give up and call
> __add__ again.

Uh... please pretend I didn't say that.
You are right, I haven't gotten coerce() straight yet.

> In some cases it might help to call coerce() by hand, but I note the
> ref manual says 'In Python 3.0, coercion will not be supported.'.

Even so, coerce() by hand seems pretty cumbersome.  The code I could
come up with for the general case is as follows.  Am I missing something
again?

    class Myclass(object):
        def __add__(self, other):
            if not isinstance(other, Myclass):
                newself, other = coerce(self, other)
                if newself != self:
                    return newself.__add__(other)
                # Or maybe the above should test if
                # newself.__class__ != self.__class__, and do
                # self = newself if they have the same class.
            ...real __add__(Myclass, Myclass) starts here...

-- 
Hallvard



More information about the Python-list mailing list