Coerce that can pay attention to type of operation

Martin von Loewis loewis at informatik.hu-berlin.de
Sun Oct 1 16:08:50 EDT 2000


jepler.lnk at lnk.ispi.net (jepler epler) writes:

> However, for __pow__, I wish that I could follow another rule, where:
> 	r = Ratio()
> 	f = 1.0
> 	i = 1
> 
> 	r**f -> float(r) ** f
> 	r**i -> Ratio(r.num ** i, r.den ** i)
> 	f**r -> f ** float(r)
> 	i**r -> i ** float(r)

You did not specify what outcome you want to get from 3.14+Ratio(1,2)
- I'll assume that the result should be 3.14+0.5. So inside coerce, if
one argument is float, you have to coerce the rational number to float
as well (in general: of one type is mathematically a superset of the
other, coerce to the former; think of 'float' == 'real numbers' here
(*)).

With that, you'd get the r**f and f**r case covered.

For the r**i case, I suggest that you still coerce the integer into a
rational. Then you'll need to implement a __pow__, which will deal
with the r**r case. If the exponent happens to be an integral number,
you implement your r**i formula (remember to deal with negative
numbers); if the exponent is not natural, convert to float and compute
the power then.

> Am I missing a better way to do what I want?  If not, is there any
> merit to the idea of __coerce3__?

There are places where you can't tell, e.g when invoking coerce
directly. Adding new magic functions is a bad idea in general, since
it puts a burden onto any class object: the interpreter would always
call __coerce3__ on both objects, then __coerce__, and then the
operation. The extra lookup is bad for performance, especially if the
class also has a __getattr__.

Nevertheless, please write a PEP (http://python.sourceforge.net/peps)
on this subject, or have a look at PEP 208 :-). Something should be
done, probably, but it will need a lot of planning.

Regards,
Martin

(*) I know that technically, rational numbers are a superset of
floating point numbers (which are rationals with some base two
denominator). I understand you don't want to treat them that way,
though.



More information about the Python-list mailing list