Issue with new-style classes and operators

Robin Munn rmunn at pobox.com
Wed Nov 27 11:19:38 EST 2002


Jan Decaluwe <jan at jandecaluwe.com> wrote:
> Alex Martelli wrote:
>> 
>> Jan Decaluwe wrote:
>> 
[foo.__add__ treated differently than foo + 4]
>> >
>> > I don't think is can be the intention. Or can it?
>> 
>> Yes it can.  The idea is that operators should rely on special
>> methods defined by the TYPE (class) of the object they're working
>> on, NOT on special methods defined just by the OBJECT itself and
>> not by its class. 
> 
> But what makes operator methods so special that they should be treated
> so differently from ordinary methods?
> 
> As far as I am concerned, operator syntax is just convenience, not 
> concept. The line between operators and ordinary methods is thin
> and arbitrary. 
> 
> For example, take 's.extend(x)', with s a list. The documentation states 
> that it is the same as 's[len(s):len(s)] = x'. Another way to
> do it is 's += x'.
> 
> Yet, if you try it with my example class, the 'extend' would work fine,
> and while the 2 operator-style statements would give a type error.
> What's logical about that?

I would agree with this. I was experimenting with subclassing list the
other day and discovered to my surprise that overriding setitem() and
setslice() had no effect on l.extend(x). This struck me as violating the
Principle of Least Surprise, *especially* since the documentation had
said that l.extend(x) was equivalent to l[len(l):len(l)] = x.

This feels like a wart that needs to be fixed. I don't know what the
right answer will be. Maybe behavior needs to change in some way, or
maybe the documentation needs to be fixed to explain *in detail* what
actually happens when you subclass built-in types. But this has been
bugging me, and I think I want to see it fixed somehow.

-- 
Robin Munn <rmunn at pobox.com>
http://www.rmunn.com/
PGP key ID: 0x6AFB6838    50FF 2478 CFFB 081A 8338  54F7 845D ACFD 6AFB 6838



More information about the Python-list mailing list