[Python-Dev] Symmetry arguments for API expansion

Guido van Rossum guido at python.org
Tue Mar 13 13:43:29 EDT 2018


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 at 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)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-dev/attachments/20180313/c4747049/attachment.html>


More information about the Python-Dev mailing list