[Python-Dev] Symmetry arguments for API expansion

Nick Coghlan ncoghlan at gmail.com
Wed Mar 21 08:34:27 EDT 2018


On 14 March 2018 at 08:29, Tim Peters <tim.peters at gmail.com> wrote:

> [Tim]
> >> An obvious way to extend it is for Fraction() to look for a special
> >> method too, say "_as_integer_ratio()".
>
> [Greg Ewing]
> > Why not __as_integer_ratio__?
>
> Because. at this point, that would be beating a dead horse ;-)
>

I'm not so sure about that, as if we define a protocol method for it, then
we'd presumably also define an "operator.as_integer_ratio" function, and
that function could check __index__ in addition to checking the new
protocol method.

For example:

    def as_integer_ratio(n):
        # Automatically accept true integers
        if hasattr(n, "__index__"):
            return (n.__index__(), 1)
        # New reserved protocol method
        if hasattr(n, "__integer_ratio__"):
            return n.__integer_ratio__()
        # Historical public protocol method
        if hasattr(n, "as_integer_ratio"):
            return n.as_integer_ratio()
        # Check for lossless integer conversion
        try:
            int_n = int(n)
        except TypeError:
            pass
        else:
            if int_n == n:
                return (int_n, 1)
        raise TypeError(f"{type(n)} does not support conversion to an
integer ratio")

Similarly, on the "operator.is_integer" front:

    def is_integer(n):
        # Automatically accept true integers
        if hasattr(n, "__index__"):
            return True
        # New reserved protocol method
        if hasattr(n, "__is_integer__"):
            return n.__is_integer__()
        # Historical public protocol method
        if hasattr(n, "is_integer"):
            return n.is_integer()
        # As a last resort, check for lossless int conversion
        return int(n) == n

Cheers,
Nick.

P.S. I've suggested "operator" as a possible location, since that's where
we put "operator.index", and it's a low level module that doesn't bring in
any transitive dependencies. However, putting these protocol wrappers
somewhere else (e.g. in "math" or "numbers") may also make sense.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-dev/attachments/20180321/690d1b39/attachment.html>


More information about the Python-Dev mailing list