diff --git a/Lib/test/test_float.py b/Lib/test/test_float.py index cabeb16c42b..b52b1db9e46 100644 --- a/Lib/test/test_float.py +++ b/Lib/test/test_float.py @@ -914,6 +914,15 @@ class InfNanTest(unittest.TestCase): self.assertFalse(NAN.is_inf()) self.assertFalse((0.).is_inf()) + def test_hash_inf(self): + # the actual values here should be regarded as an + # implementation detail, but they need to be + # identical to those used in the Decimal module. + self.assertEqual(hash(float('inf')), 314159) + self.assertEqual(hash(float('-inf')), -271828) + self.assertEqual(hash(float('nan')), 0) + + fromHex = float.fromhex toHex = float.hex class HexFloatTestCase(unittest.TestCase): diff --git a/Objects/object.c b/Objects/object.c index a332c6c85e3..0b22e380e78 100644 --- a/Objects/object.c +++ b/Objects/object.c @@ -656,15 +656,15 @@ _Py_HashDouble(double v) * of mapping keys will turn out weird. */ + if (Py_IS_INFINITY(v)) + /* can't convert to long int -- arbitrary */ + v = v < 0 ? -271828.0 : 314159.0; fractpart = modf(v, &intpart); if (fractpart == 0.0) { /* This must return the same hash as an equal int or long. */ if (intpart > LONG_MAX/2 || -intpart > LONG_MAX/2) { /* Convert to long and use its hash. */ PyObject *plong; /* converted to Python long */ - if (Py_IS_INFINITY(intpart)) - /* can't convert to long int -- arbitrary */ - v = v < 0 ? -271828.0 : 314159.0; plong = PyLong_FromDouble(v); if (plong == NULL) return -1;