From fc33d4ce0a2a89d26c30cd31ccc1992eb495aff0 Mon Sep 17 00:00:00 2001 From: Mark Dickinson Date: Fri, 24 Aug 2012 18:53:10 +0100 Subject: [PATCH] Issue #15544: Fix Decimal.__float__ to work with payload-carrying NaNs. --- Lib/decimal.py | 8 +++++++- Lib/test/test_decimal.py | 16 ++++++++++++++++ Misc/NEWS | 2 ++ Modules/_decimal/_decimal.c | 18 +++++++++++++++++- 4 files changed, 42 insertions(+), 2 deletions(-) diff --git a/Lib/decimal.py b/Lib/decimal.py index 6bd655bdb75..b74ab0134d9 100644 --- a/Lib/decimal.py +++ b/Lib/decimal.py @@ -1601,7 +1601,13 @@ class Decimal(object): def __float__(self): """Float representation.""" - return float(str(self)) + if self._isnan(): + if self.is_snan(): + raise ValueError("Cannot convert signaling NaN to float") + s = "-nan" if self._sign else "nan" + else: + s = str(self) + return float(s) def __int__(self): """Converts self to an int, truncating if necessary.""" diff --git a/Lib/test/test_decimal.py b/Lib/test/test_decimal.py index 781df1f290f..d00ed5aa40c 100644 --- a/Lib/test/test_decimal.py +++ b/Lib/test/test_decimal.py @@ -1942,6 +1942,22 @@ class UsabilityTest(unittest.TestCase): for d, n, r in test_triples: self.assertEqual(str(round(Decimal(d), n)), r) + def test_nan_to_float(self): + # Test conversions of decimal NANs to float. + # See http://bugs.python.org/issue15544 + Decimal = self.decimal.Decimal + for s in ('nan', 'nan1234', '-nan', '-nan2468'): + f = float(Decimal(s)) + self.assertTrue(math.isnan(f)) + sign = math.copysign(1.0, f) + self.assertEqual(sign, -1.0 if s.startswith('-') else 1.0) + + def test_snan_to_float(self): + Decimal = self.decimal.Decimal + for s in ('snan', '-snan', 'snan1357', '-snan1234'): + d = Decimal(s) + self.assertRaises(ValueError, float, d) + def test_eval_round_trip(self): Decimal = self.decimal.Decimal diff --git a/Misc/NEWS b/Misc/NEWS index 6d046ff17ab..3521001b2d0 100644 --- a/Misc/NEWS +++ b/Misc/NEWS @@ -32,6 +32,8 @@ Core and Builtins Library ------- +- Issue #15544: Fix Decimal.__float__ to work with payload-carrying NaNs. + - Issue #15776: Allow pyvenv to work in existing directory with --clean. - Issue #15249: BytesGenerator now correctly mangles From lines (when diff --git a/Modules/_decimal/_decimal.c b/Modules/_decimal/_decimal.c index ecca411fc4b..15c64e215d7 100644 --- a/Modules/_decimal/_decimal.c +++ b/Modules/_decimal/_decimal.c @@ -3357,7 +3357,23 @@ PyDec_AsFloat(PyObject *dec) { PyObject *f, *s; - s = dec_str(dec); + if (mpd_isnan(MPD(dec))) { + if (mpd_issnan(MPD(dec))) { + PyErr_SetString(PyExc_ValueError, + "cannot convert signaling NaN to float"); + return NULL; + } + if (mpd_isnegative(MPD(dec))) { + s = PyUnicode_FromString("-nan"); + } + else { + s = PyUnicode_FromString("nan"); + } + } + else { + s = dec_str(dec); + } + if (s == NULL) { return NULL; }