Coerce and multimethods (was Re: Inefficiency of __getattr__)
Martin von Loewis
loewis at informatik.hu-berlin.de
Tue Oct 3 11:04:06 EDT 2000
hzhu at users.sourceforge.net (Huaiyu Zhu) writes:
> That would make it quite useless in my case. Yet the simple do-nothing
> __coerce__ still consumes as much time as the actual computation, although
> __getattr__ uses 6 times more.
In your case, the most efficient implementation would be
def __coerce__(self, other):
return (0,0)
Then, it won't invoke another __add__ on any object - which is ok,
since your __add__ would return None, anyway :-)
> Sometime ago there was a brief discussion of multimethods here. The idea is
> that a+b will be dependent on the classes/types of both a and b. I did not
> quite understand it at the time. But now it looks to me like that
> __coerce__ is simply an awkward way of doing it half-heartedly.
Well, coercion is intended to do just that: coerce the arguments to a
common type. In arithmethic operations, it is an elegant way to deal
with the subset/superset problem. Since
Natural \subset Rational \subset Real \subset Complex
it is straight-forward to assume that number-like objects support
coercion.
> In another thread yesterday someone suggested a three way coerce, using the
> operation as a third argument to fine tune the coersion. That would still
> leave out the info about the original operands, though. A multimethod would
> solve all these in a much cleaner way.
I don't understand. If you want to operate on the original operands,
you don't need any coercion...
> Short of that, maybe we should propose to use __coerce__ only for builin
> (numeric) types and explicit coerce calls?
No, that would be a significant change, breaking compatibility.
> What are the most significant applications that use coerce, anyway?
Numerical types, i.e. objects implementing __add__, __mul__, and so
on. If your type is not numerical, perhaps it should not provide an
__add__?
In any case, contributions to
http://python.sourceforge.net/peps/pep-0208.html are welcome.
Regards,
Martin
More information about the Python-list
mailing list