Re: [Python-Dev] Symmetry arguments for API expansion

2018年3月21日 05:37:16 -0700

On 14 March 2018 at 08:29, Tim Peters <[email protected]> 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 | [email protected] | Brisbane, Australia
_______________________________________________
Python-Dev mailing list
[email protected]
https://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
https://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com

Reply via email to