Hack request: rational numbers

Anton Mellit mellit at gmail.com
Fri Oct 26 16:02:01 EDT 2007


> Hi!
>
> I am using rational numbers from the gmpy module and I find that creating
> one in Python using
>
>>>> mpq(3,4)
>
> is rather clumsy. Clearly, minimal representation of this rational number
> is
>
>    3/4
>
> but in Python this expression has different meaning.

Hi,
I am writing an interface module with the PARI library and I had the
same question. So I implemented division operator for my new type
which of course did not work if both division arguments are integers.
Say 3/4 gives zero. But I discovered very simple hack. I add the
following string to my module initialization function:

	PyInt_Type.tp_as_number->nb_divide = gen_div;

Here gen_div is the function I use for division of objects of my new type.

This solution is pretty nice since I do not have to make changes into
python or interactive shell. It is even better to make a function
which would 'turn on/off' my division. It is strange that it is only
possible to do such things in C code, I cannot do it from python.

Anton



More information about the Python-list mailing list