Issue 3285: Fraction.from_any() - Python tracker (original) (raw)
After exercising the fractions module, I've found it problematic that there isn't a unified constructor to handle mixed data input types.
For example, when updating the accurate summation recipe at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/393090 to show how it could be done with rational arithmetic. Handling mixed-type inputs required writing a factory function:
def makefrac(x):
if isinstance(x, Decimal):
return Fraction.from_decimal(x)
if isinstance(x, float):
return Fraction.from_float(x)
return Fraction(x)
That function supported a clean version of the recipe:
def frsum(iterable):
return float(sum(map(makefrac, iterable)))
It would have been much better if that functionality were built into the class definition. See attached patch.