__coerce__ vs. new-style classes

John Roth newsgroups at jhrothjr.com
Mon Aug 2 13:18:14 EDT 2004


"Hallvard B Furuseth" <h.b.furuseth at usit.uio.no> wrote in message
news:HBF.20040802t150 at bombur.uio.no...
> Why do new-style classes disable __coerce__()?
> It seems cumbersome to have to write a whole set of methods (e.g.
> __add__, __radd__, etc.) to get the same effect.  Is there some way to
> automatically generate those methods, or are we simply not supposed to
> do coercion for some reason?

I'm mildly confused by your example. __coerce__()
converts the arguements to a common type, and then
presumably requests that type to do the operation. That
type might not be one of the two original types!

It's not the same thing as the __op__, __rop__
pair. That simply allows the right object to do the
operation if the left object can't. (Also see 3.3.8
of the language reference for an exception to that
rule.)

The notion of type coercion makes a great deal of sense
in languages such as C, where you have 8 integer types
and 3 float types, but abstracting it out as a separate
operation makes very little sense in Python, where you
have 3 numeric types (int, long and float) and two string
types (normal and unicode). The overhead of doing
coercion as a separate operation simply doesn't make
a lot of sense.

At least, that's the way I understand it. Section 3.3.8
(Coercion Rules) of the 2.3 Language Reference gives
the official reasons for moving away from doing coercion
as part of operations. It simply got to complex to
document properly.

I suppose if you have a use case for __coerce__ in a
real world cluster of non-numeric types, you could
get Guido to reconsider.

John Roth
>
> -- 
> Hallvard





More information about the Python-list mailing list