]> granicus.if.org Git - python/commitdiff
Make Fraction(-1).__hash__() return -2 rather than -1 (see issue 10356).
authorMark Dickinson <dickinsm@gmail.com>
Sat, 13 Nov 2010 10:27:38 +0000 (10:27 +0000)
committerMark Dickinson <dickinsm@gmail.com>
Sat, 13 Nov 2010 10:27:38 +0000 (10:27 +0000)
Lib/fractions.py
Lib/test/test_fractions.py
Misc/NEWS

index 51e67e22eade0ea5f33ba3608c326bb1e79afef6..8be52d2db88ca6afda2f18786e6a41b5de62f279 100644 (file)
@@ -528,12 +528,8 @@ class Fraction(numbers.Rational):
             return Fraction(round(self / shift) * shift)
 
     def __hash__(self):
-        """hash(self)
+        """hash(self)"""
 
-        Tricky because values that are exactly representable as a
-        float must have the same hash as that float.
-
-        """
         # XXX since this method is expensive, consider caching the result
 
         # In order to make sure that the hash of a Fraction agrees
@@ -550,7 +546,8 @@ class Fraction(numbers.Rational):
             hash_ = _PyHASH_INF
         else:
             hash_ = abs(self._numerator) * dinv % _PyHASH_MODULUS
-        return hash_ if self >= 0 else -hash_
+        result = hash_ if self >= 0 else -hash_
+        return -2 if result == -1 else result
 
     def __eq__(a, b):
         """a == b"""
index a41fd9c37c26fb36737fb79952078dc7dcd214e7..c28f06c5a2a465981efd5667f10351eb718ea950 100644 (file)
@@ -546,6 +546,9 @@ class FractionTest(unittest.TestCase):
         self.assertEquals(hash(2.5), hash(F(5, 2)))
         self.assertEquals(hash(10**50), hash(F(10**50)))
         self.assertNotEquals(hash(float(10**23)), hash(F(10**23)))
+        # Check that __hash__ produces the same value as hash(), for
+        # consistency with int and Decimal.  (See issue #10356.)
+        self.assertEquals(hash(F(-1)), F(-1).__hash__())
 
     def testApproximatePi(self):
         # Algorithm borrowed from
index 9a847e47ff9a9d818ab7c0746f57dd3795f6f04c..2887040d1e54d08c93c5ab8de398e13413ad1775 100644 (file)
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -63,6 +63,9 @@ Core and Builtins
 Library
 -------
 
+- Fix Fraction.__hash__ so that Fraction.__hash__(-1) is -2.  (See
+  also issue #10356.)
+
 - Issue #4471: Add the IMAP.starttls() method to enable encryption on
   standard IMAP4 connections.  Original patch by Lorenzo M. Catucci.