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