gmpy/decimal interoperation

Alex Martelli aleax at mail.comcast.net
Mon Nov 14 09:50:54 EST 2005


Raymond L. Buvel <levub137 at wi.rr.com> wrote:
   ...
> This is a bit off topic but I would like to know how you would go about
> doing an implicit operation with an mpz and Decimal becoming a Decimal.

I would tweak Decimal.__new__ to accept an mpz and perform an int() on
it before proceeding as it does now, for example.

>  I would like to use something like this to make the float and complex
> types more interoperable with mpq and cmpq in my clnum module
> (http://calcrpnpy.sourceforge.net/clnumManual.html).  In those cases, I
> would like the mpq to degrade to float and the cmpq to degrade to
> complex (right now they just raise exceptions).  Seems like you need to
> either modify the target type to recognize the new one or the code has
> to get very complex to handle all the combinations.

Modifying the target type is indeed what I had in mind (for Decimal).
As long as the target-type is Python-coded, you can substitute its
__new__ with a wrapped version.  Unfortunately, float and complex
aren't; but fortunately, Python does have for these cases appropriate
special methods/slot that your SOURCE type can implement.  In gmpy, I
have float 'upgraded' to mpq (with a Stern-Brocot heuristic), but it
wouldn't be any harder to have the mpq 'degrade' to float instead.


Alex



More information about the Python-list mailing list