summaryrefslogtreecommitdiffstats
path: root/Lib/fractions.py
diff options
context:
space:
mode:
authorJeffrey Yasskin <jyasskin@gmail.com>2008-02-14 06:12:24 (GMT)
committerJeffrey Yasskin <jyasskin@gmail.com>2008-02-14 06:12:24 (GMT)
commit1c214d6c942df3fc7af548f7c7e10961dcaba3ee (patch)
treeed69739c69b8a5f6b2c3fb922fd08d373dfaf64c /Lib/fractions.py
parentabe32371878dcaea31c835e10144fdaa2eca6492 (diff)
downloadcpython-1c214d6c942df3fc7af548f7c7e10961dcaba3ee.zip
cpython-1c214d6c942df3fc7af548f7c7e10961dcaba3ee.tar.gz
cpython-1c214d6c942df3fc7af548f7c7e10961dcaba3ee.tar.bz2
Performance optimizations on Fraction's constructor.
./python.exe -m timeit -s 'from fractions import Fraction' 'Fraction(3)` 31.7 usec/loop -> 9.2 usec/loop ./python.exe -m timeit -s 'from fractions import Fraction' 'Fraction(3, 2)'` 27.7 usec/loop -> 9.32 usec/loop ./python.exe -m timeit -s 'from fractions import Fraction; f = Fraction(3, 2)' 'Fraction(f)' 31.9 usec/loop -> 14.3 usec/loop
Diffstat (limited to 'Lib/fractions.py')
-rwxr-xr-xLib/fractions.py20
1 files changed, 9 insertions, 11 deletions
diff --git a/Lib/fractions.py b/Lib/fractions.py
index 53ff785..9dd49b1 100755
--- a/Lib/fractions.py
+++ b/Lib/fractions.py
@@ -64,7 +64,7 @@ class Fraction(Rational):
"""
self = super(Fraction, cls).__new__(cls)
- if denominator == 1:
+ if type(numerator) not in (int, long) and denominator == 1:
if isinstance(numerator, basestring):
# Handle construction from strings.
input = numerator
@@ -86,24 +86,22 @@ class Fraction(Rational):
if m.group('sign') == '-':
numerator = -numerator
- elif (not isinstance(numerator, numbers.Integral) and
- isinstance(numerator, Rational)):
- # Handle copies from other rationals.
+ elif isinstance(numerator, Rational):
+ # Handle copies from other rationals. Integrals get
+ # caught here too, but it doesn't matter because
+ # denominator is already 1.
other_rational = numerator
numerator = other_rational.numerator
denominator = other_rational.denominator
- if (not isinstance(numerator, numbers.Integral) or
- not isinstance(denominator, numbers.Integral)):
- raise TypeError("Fraction(%(numerator)s, %(denominator)s):"
- " Both arguments must be integral." % locals())
-
if denominator == 0:
raise ZeroDivisionError('Fraction(%s, 0)' % numerator)
+ numerator = numerator.__index__()
+ denominator = denominator.__index__()
g = gcd(numerator, denominator)
- self._numerator = int(numerator // g)
- self._denominator = int(denominator // g)
+ self._numerator = numerator // g
+ self._denominator = denominator // g
return self
@classmethod