[issue23975] numbers.Rational implements __float__ incorrectly
Wolfgang Maier
report at bugs.python.org
Mon Apr 27 15:08:22 CEST 2015
Wolfgang Maier added the comment:
After considering this for a while, I think:
return float(self.numerator / self.denominator)
is the best solution:
* it is simple and works reasonably well as a default
* it fixes Rational.__float__ for cases, in which numerator / denominator returns a custom Real instance
* in the problematic scenario brought up by Mark, in which truediv of the numerator and denominator returns another Rational creating a potentially infinite recursion, a RuntimeError will be raised when the maximum recursion limit is reached. This is not an unheard of error to run into while trying to implement a custom numeric type and will provide reasonable (though not ideal) information about the problem.
* the workaround for the above is obvious: it is ok for self.numerator / self.denominator to return a Rational instance, but its type should overwrite Rational.__float__ to break the recursion. This could get documented in the docstring of Rational.__float__.
I've attached a tentative patch.
----------
keywords: +patch
Added file: http://bugs.python.org/file39217/Rational.__float__.patch
_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue23975>
_______________________________________
More information about the Python-bugs-list
mailing list