[issue23975] numbers.Rational implements __float__ incorrectly

Wolfgang Maier report at bugs.python.org
Mon Apr 20 15:05:02 CEST 2015


Wolfgang Maier added the comment:

> Is it not reasonable to simply say that implementations of numbers.Rational which allow the numerator and denominator to have types for which true division doesn't return a float, have to provide their own implementation of __float__()?

Unfortunately, the Rational type cannot always know what its numerator or denominator supports.
Look at fractions.Fraction: its only requirement for numerator and denominator is that they both should be Rational instances.
So a hypothetical MyInt like Mark describes it could be perfectly acceptable for Fraction except that it would fail to convert it to float.
 
> It's certainly less convenient, and probably surprising for users, but the alternative is trying to work around broken integer types - after all numbers.Complex.__truediv__ says "Should promote to float when necessary" in the docstring, which to me says that a type where a/b doesn't return a float doesn't conform to the numeric tower.
> 

I do read this docstring differently. To me, it means should promote to float if there is no other way to express the result (like when your custom type system does not define its own Float type).
It would, in fact, be really bad for custom type implementors if they would be forced to leave their type system when doing divisions.

> Alternatively, return int(self.numerator) / int(self.denominator). After all, a fraction whose numerator can't be represented as a Python (unlimited precision) integer is a pretty odd sort of fraction...

The problem here is that self.numerator and/or self.denominator could both be Rational instances again, which are not expressible as a Python integer and, thus, are not enforced to provide __int__ by the numbers ABC.

----------

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue23975>
_______________________________________


More information about the Python-bugs-list mailing list