diff --git a/Lib/decimal.py b/Lib/decimal.py index 1f5c920d795..a87a4a54110 100644 --- a/Lib/decimal.py +++ b/Lib/decimal.py @@ -1555,10 +1555,9 @@ class Decimal(object): """Converts self to an int, truncating if necessary.""" if self._is_special: if self._isnan(): - context = getcontext() - return context._raise_error(InvalidContext) + raise ValueError("Cannot convert NaN to integer") elif self._isinfinity(): - raise OverflowError("Cannot convert infinity to int") + raise OverflowError("Cannot convert infinity to integer") s = (-1)**self._sign if self._exp >= 0: return s*int(self._int)*10**self._exp diff --git a/Lib/test/test_decimal.py b/Lib/test/test_decimal.py index f7f023d22d0..50a855e9d1d 100644 --- a/Lib/test/test_decimal.py +++ b/Lib/test/test_decimal.py @@ -1489,6 +1489,16 @@ class DecimalPythonAPItests(unittest.TestCase): r = d.to_integral(ROUND_DOWN) self.assertEqual(Decimal(int(d)), r) + self.assertRaises(ValueError, int, Decimal('-nan')) + self.assertRaises(ValueError, int, Decimal('snan')) + self.assertRaises(OverflowError, int, Decimal('inf')) + self.assertRaises(OverflowError, int, Decimal('-inf')) + + self.assertRaises(ValueError, long, Decimal('-nan')) + self.assertRaises(ValueError, long, Decimal('snan')) + self.assertRaises(OverflowError, long, Decimal('inf')) + self.assertRaises(OverflowError, long, Decimal('-inf')) + def test_trunc(self): for x in range(-250, 250): s = '%0.2f' % (x / 100.0) diff --git a/Misc/NEWS b/Misc/NEWS index fe281cf0149..daea539f8c6 100644 --- a/Misc/NEWS +++ b/Misc/NEWS @@ -366,6 +366,10 @@ Core and Builtins Library ------- +- Issue #6795: int(Decimal('nan')) now raises ValueError instead of + returning NaN or raising InvalidContext. Also, fix infinite recursion + in long(Decimal('nan')). + - Issue #6850: Fix bug in Decimal._parse_format_specifier for formats with no type specifier.