Spurious coercing? [was: Re: 'if foo' calls getattr?!?]

François Pinard pinard at iro.umontreal.ca
Tue Jun 6 15:23:04 EDT 2000


Moshe Zadka <moshez at math.huji.ac.il> écrit:

> On 6 Jun 2000, [ISO-8859-1] François Pinard wrote:

> > And I would presume that if __cmp__ happened to be found, a call to
> > __coerce__ would be tried before going any further?

> Yes, indeed. The reason is that Python tries very hard *not* to be
> smart: the opposite of smart, in this case, being predictable. If you
> know __coerce__ is always called before binary operators take place,
> your code can be that much simpler.

I saw many emails in which people were surprised by Python behaviour, and I
interpret the surprise as a sign that predictability suffers.  For example,
A.__cmp__(B) will not be called for an equality comparison when A "is" B.
Yet, given the meaning of __cmp__, this sounds absolutely correct to me.

Also given the meaning of __coerce__, I would consider just equally correct
to avoid calling A.__coerce__(B) when type(A) "is" type(B).  The spontaneous
predictable thing, here, is that __coerce__ should *not* be used when it is
evident it should not.  Python violates the principle of least surprise,
here, and predictability as well, in my opinion.  That probably depends
on what one gets used to predict! :-).

If it was a good idea to optimise the __cmp__ case, it is also a good
idea to optimise __coerce__.  Also given that not doing it for __coerce__
implies a supplementary (small) burden on the programmer, usually more
than for the __cmp__ case.  I do not see any advantage for not doing it.

-- 
François Pinard   http://www.iro.umontreal.ca/~pinard






More information about the Python-list mailing list