diff options
author | Serhiy Storchaka <storchaka@gmail.com> | 2015-12-29 20:34:23 (GMT) |
---|---|---|
committer | Serhiy Storchaka <storchaka@gmail.com> | 2015-12-29 20:34:23 (GMT) |
commit | 0d250bc119489fa7d094d4a3fd2fd2fa0a508145 (patch) | |
tree | 713daa0ef460e7a6744de0748ea829fefe6efb12 /Lib/fractions.py | |
parent | 5aab44b301fff2c6a7f00e24944a3360eedd7aa8 (diff) | |
download | cpython-0d250bc119489fa7d094d4a3fd2fd2fa0a508145.zip cpython-0d250bc119489fa7d094d4a3fd2fd2fa0a508145.tar.gz cpython-0d250bc119489fa7d094d4a3fd2fd2fa0a508145.tar.bz2 |
Issue #25971: Optimized creating Fractions from floats by 2 times and from
Decimals by 3 times.
Unified error messages in float.as_integer_ratio(), Decimal.as_integer_ratio(),
and Fraction constructors.
Diffstat (limited to 'Lib/fractions.py')
-rw-r--r-- | Lib/fractions.py | 32 |
1 files changed, 4 insertions, 28 deletions
diff --git a/Lib/fractions.py b/Lib/fractions.py index 60b0728..64d746b 100644 --- a/Lib/fractions.py +++ b/Lib/fractions.py @@ -125,17 +125,9 @@ class Fraction(numbers.Rational): self._denominator = numerator.denominator return self - elif isinstance(numerator, float): - # Exact conversion from float - value = Fraction.from_float(numerator) - self._numerator = value._numerator - self._denominator = value._denominator - return self - - elif isinstance(numerator, Decimal): - value = Fraction.from_decimal(numerator) - self._numerator = value._numerator - self._denominator = value._denominator + elif isinstance(numerator, (float, Decimal)): + # Exact conversion + self._numerator, self._denominator = numerator.as_integer_ratio() return self elif isinstance(numerator, str): @@ -210,10 +202,6 @@ class Fraction(numbers.Rational): elif not isinstance(f, float): raise TypeError("%s.from_float() only takes floats, not %r (%s)" % (cls.__name__, f, type(f).__name__)) - if math.isnan(f): - raise ValueError("Cannot convert %r to %s." % (f, cls.__name__)) - if math.isinf(f): - raise OverflowError("Cannot convert %r to %s." % (f, cls.__name__)) return cls(*f.as_integer_ratio()) @classmethod @@ -226,19 +214,7 @@ class Fraction(numbers.Rational): raise TypeError( "%s.from_decimal() only takes Decimals, not %r (%s)" % (cls.__name__, dec, type(dec).__name__)) - if dec.is_infinite(): - raise OverflowError( - "Cannot convert %s to %s." % (dec, cls.__name__)) - if dec.is_nan(): - raise ValueError("Cannot convert %s to %s." % (dec, cls.__name__)) - sign, digits, exp = dec.as_tuple() - digits = int(''.join(map(str, digits))) - if sign: - digits = -digits - if exp >= 0: - return cls(digits * 10 ** exp) - else: - return cls(digits, 10 ** -exp) + return cls(*dec.as_integer_ratio()) def limit_denominator(self, max_denominator=1000000): """Closest Fraction to self with denominator at most max_denominator. |