diff options
author | Georg Brandl <georg@python.org> | 2014-09-24 06:37:55 (GMT) |
---|---|---|
committer | Georg Brandl <georg@python.org> | 2014-09-24 06:37:55 (GMT) |
commit | 40f9735486a847130eb52185659a278cf369bb9e (patch) | |
tree | 75849d9408b3b2876c00d242b19ef4f224976a5b /Lib/fractions.py | |
parent | 02d39c24c44224e94cb1bd65be1b6498b363fd78 (diff) | |
download | cpython-40f9735486a847130eb52185659a278cf369bb9e.zip cpython-40f9735486a847130eb52185659a278cf369bb9e.tar.gz cpython-40f9735486a847130eb52185659a278cf369bb9e.tar.bz2 |
#22464: Speed up common Fraction operations by special-casing several
operations for int-type arguments: constructor and equality test.
Also avoid redundant property lookups in addition and subtraction.
Diffstat (limited to 'Lib/fractions.py')
-rw-r--r-- | Lib/fractions.py | 24 |
1 files changed, 17 insertions, 7 deletions
diff --git a/Lib/fractions.py b/Lib/fractions.py index 57bf7f5..5ddc84c 100644 --- a/Lib/fractions.py +++ b/Lib/fractions.py @@ -104,7 +104,12 @@ class Fraction(numbers.Rational): self = super(Fraction, cls).__new__(cls) if denominator is None: - if isinstance(numerator, numbers.Rational): + if type(numerator) is int: + self._numerator = numerator + self._denominator = 1 + return self + + elif isinstance(numerator, numbers.Rational): self._numerator = numerator.numerator self._denominator = numerator.denominator return self @@ -153,6 +158,9 @@ class Fraction(numbers.Rational): raise TypeError("argument should be a string " "or a Rational instance") + elif type(numerator) is int is type(denominator): + pass # *very* normal case + elif (isinstance(numerator, numbers.Rational) and isinstance(denominator, numbers.Rational)): numerator, denominator = ( @@ -399,17 +407,17 @@ class Fraction(numbers.Rational): def _add(a, b): """a + b""" - return Fraction(a.numerator * b.denominator + - b.numerator * a.denominator, - a.denominator * b.denominator) + da, db = a.denominator, b.denominator + return Fraction(a.numerator * db + b.numerator * da, + da * db) __add__, __radd__ = _operator_fallbacks(_add, operator.add) def _sub(a, b): """a - b""" - return Fraction(a.numerator * b.denominator - - b.numerator * a.denominator, - a.denominator * b.denominator) + da, db = a.denominator, b.denominator + return Fraction(a.numerator * db - b.numerator * da, + da * db) __sub__, __rsub__ = _operator_fallbacks(_sub, operator.sub) @@ -561,6 +569,8 @@ class Fraction(numbers.Rational): def __eq__(a, b): """a == b""" + if type(b) is int: + return a._numerator == b and a._denominator == 1 if isinstance(b, numbers.Rational): return (a._numerator == b.numerator and a._denominator == b.denominator) |