summaryrefslogtreecommitdiffstats
path: root/Lib/fractions.py
diff options
context:
space:
mode:
authorMark Dickinson <dickinsm@gmail.com>2009-04-22 18:15:25 (GMT)
committerMark Dickinson <dickinsm@gmail.com>2009-04-22 18:15:25 (GMT)
commit8100bd8431cae4b079ffc1f0c3e33ba019661994 (patch)
tree4e1d824f65678b76d2438e7a8edbc34689c4b4f3 /Lib/fractions.py
parentebafbb705cbc92e7917e2dea423c141ec2b276b4 (diff)
downloadcpython-8100bd8431cae4b079ffc1f0c3e33ba019661994.zip
cpython-8100bd8431cae4b079ffc1f0c3e33ba019661994.tar.gz
cpython-8100bd8431cae4b079ffc1f0c3e33ba019661994.tar.bz2
Issue #5812: make Fraction('1e-6') valid. Backport of r71806.
Diffstat (limited to 'Lib/fractions.py')
-rwxr-xr-xLib/fractions.py45
1 files changed, 26 insertions, 19 deletions
diff --git a/Lib/fractions.py b/Lib/fractions.py
index 446ad8e..7db6b5b 100755
--- a/Lib/fractions.py
+++ b/Lib/fractions.py
@@ -30,13 +30,14 @@ _RATIONAL_FORMAT = re.compile(r"""
(?P<sign>[-+]?) # an optional sign, then
(?=\d|\.\d) # lookahead for digit or .digit
(?P<num>\d*) # numerator (possibly empty)
- (?: # followed by an optional
- /(?P<denom>\d+) # / and denominator
+ (?: # followed by
+ (?:/(?P<denom>\d+))? # an optional denominator
| # or
- \.(?P<decimal>\d*) # decimal point and fractional part
- )?
+ (?:\.(?P<decimal>\d*))? # an optional fractional part
+ (?:E(?P<exp>[-+]?\d+))? # and optional exponent
+ )
\s*\Z # and optional whitespace to finish
-""", re.VERBOSE)
+""", re.VERBOSE | re.IGNORECASE)
class Fraction(Rational):
@@ -67,22 +68,28 @@ class Fraction(Rational):
if type(numerator) not in (int, long) and denominator == 1:
if isinstance(numerator, basestring):
# Handle construction from strings.
- input = numerator
- m = _RATIONAL_FORMAT.match(input)
+ m = _RATIONAL_FORMAT.match(numerator)
if m is None:
- raise ValueError('Invalid literal for Fraction: %r' % input)
- numerator = m.group('num')
- decimal = m.group('decimal')
- if decimal:
- # The literal is a decimal number.
- numerator = int(numerator + decimal)
- denominator = 10**len(decimal)
+ raise ValueError('Invalid literal for Fraction: %r' %
+ numerator)
+ numerator = int(m.group('num') or '0')
+ denom = m.group('denom')
+ if denom:
+ denominator = int(denom)
else:
- # The literal is an integer or fraction.
- numerator = int(numerator)
- # Default denominator to 1.
- denominator = int(m.group('denom') or 1)
-
+ denominator = 1
+ decimal = m.group('decimal')
+ if decimal:
+ scale = 10**len(decimal)
+ numerator = numerator * scale + int(decimal)
+ denominator *= scale
+ exp = m.group('exp')
+ if exp:
+ exp = int(exp)
+ if exp >= 0:
+ numerator *= 10**exp
+ else:
+ denominator *= 10**-exp
if m.group('sign') == '-':
numerator = -numerator