(original) (raw)

So let's make as\_integer\_ratio() the standard protocol for "how to make a Fraction out of a number that doesn't implement numbers.Rational". We already have two examples of this (float and Decimal) and perhaps numpy or the sometimes proposed fixed-width decimal type can benefit from it too. If this means we should add it to int, that's fine with me.

On Tue, Mar 13, 2018 at 9:37 AM, Tim Peters <tim.peters@gmail.com> wrote:
\[Tim\]
>> At heart, the Fraction() constructor is \_all about\_ creating integer
\>> ratios, so is the most natural place to put knowledge of how to do so.
\>> A protocol for allowing new numeric types to get converted to Fraction
\>> would be more generally useful than just a weird method only datetime
\>> uses ;-)

\[Guido\]
> Ironically, the various Fraction constructors \*calls\* as\_integer\_ratio() for
\> floats and Decimals. From which follows IMO that the float and Decimal
\> classes are the right place to encapsulate the knowledge on how to do it.

It appears that as\_integer\_ratio was slammed into floats and Decimals
precisely \_so that\_ Fraction() could call them, while Fraction has its
own self-contained knowledge of how to convert ints and Fractions and
strings and numbers.Rationals to Fraction (and the former types don't
support as\_integer\_ratio).

That's fine, but my objection is subtler: the actual answer to "can
this thing be converted to an integer ratio?" is not "does it support
as\_integer\_ratio?", but rather "can Fraction() deal with it?" - and
there's currently no way for a new numeric type to say "and here's how
I can be converted to Fraction".

An obvious way to extend it is for Fraction() to look for a special
method too, say "\_as\_integer\_ratio()". The leading underscore would
reflect the truth: that this wasn't really intended to be a public
method on its own, but is an internal protocol for use by the
Fraction() constructor.

Then it would be obvious that, e.g., it would be just plain stupid ;-)
for \`int\` to bother implementing \_as\_integer\_ratio. The only real
point of the method is to play nice with the Fraction constructor.
\_As is\_, it's jarring that int.as\_integer\_ratio() doesn't exist - for
the same reason it's jarring int.hex() doesn't exist.

If Mark or I wanted to use float.\_as\_integer\_ratio() directly too,
that's fine: we're numeric grownups and won't throw a hissy fit if
ints don't support it too ;-)



--
--Guido van Rossum (python.org/\~guido)