Issue 1780: Allow leading and trailing whitespace in Decimal constructor,
when constructing from a string. Disallow trailing newlines in
Context.create_decimal.
diff --git a/Lib/decimal.py b/Lib/decimal.py
index 8b54821..7e24516 100644
--- a/Lib/decimal.py
+++ b/Lib/decimal.py
@@ -523,6 +523,8 @@
Decimal("314")
>>> Decimal(Decimal(314)) # another decimal instance
Decimal("314")
+ >>> Decimal(' 3.14 \\n') # leading and trailing whitespace okay
+ Decimal("3.14")
"""
# Note that the coefficient, self._int, is actually stored as
@@ -538,7 +540,7 @@
# From a string
# REs insist on real strings, so we can too.
if isinstance(value, basestring):
- m = _parser(value)
+ m = _parser(value.strip())
if m is None:
if context is None:
context = getcontext()
@@ -3533,7 +3535,16 @@
return rounding
def create_decimal(self, num='0'):
- """Creates a new Decimal instance but using self as context."""
+ """Creates a new Decimal instance but using self as context.
+
+ This method implements the to-number operation of the
+ IBM Decimal specification."""
+
+ if isinstance(num, basestring) and num != num.strip():
+ return self._raise_error(ConversionSyntax,
+ "no trailing or leading whitespace is "
+ "permitted.")
+
d = Decimal(num, context=self)
if d._isnan() and len(d._int) > self.prec - self._clamp:
return self._raise_error(ConversionSyntax,
@@ -5148,7 +5159,7 @@
(?P<diag>\d*) # with (possibly empty) diagnostic information.
)
# \s*
- $
+ \Z
""", re.VERBOSE | re.IGNORECASE).match
_all_zeros = re.compile('0*$').match
diff --git a/Lib/test/test_decimal.py b/Lib/test/test_decimal.py
index 03cff60..2135637 100644
--- a/Lib/test/test_decimal.py
+++ b/Lib/test/test_decimal.py
@@ -429,6 +429,10 @@
#just not a number
self.assertEqual(str(Decimal('ugly')), 'NaN')
+ #leading and trailing whitespace permitted
+ self.assertEqual(str(Decimal('1.3E4 \n')), '1.3E+4')
+ self.assertEqual(str(Decimal(' -7.89')), '-7.89')
+
def test_explicit_from_tuples(self):
#zero
@@ -517,6 +521,10 @@
self.assertEqual(str(d), '456789')
d = nc.create_decimal('456789')
self.assertEqual(str(d), '4.57E+5')
+ # leading and trailing whitespace should result in a NaN;
+ # spaces are already checked in Cowlishaw's test-suite, so
+ # here we just check that a trailing newline results in a NaN
+ self.assertEqual(str(nc.create_decimal('3.14\n')), 'NaN')
# from tuples
d = Decimal( (1, (4, 3, 4, 9, 1, 3, 5, 3, 4), -25) )