Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit fec6620

Browse files
committed
Make Fraction(-1).__hash__() return -2 rather than -1 (see issue 10356).
1 parent 24854ca commit fec6620

3 files changed

Lines changed: 9 additions & 6 deletions

File tree

Lib/fractions.py

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -528,12 +528,8 @@ def __round__(self, ndigits=None):
528528
return Fraction(round(self / shift) * shift)
529529

530530
def __hash__(self):
531-
"""hash(self)
531+
"""hash(self)"""
532532

533-
Tricky because values that are exactly representable as a
534-
float must have the same hash as that float.
535-
536-
"""
537533
# XXX since this method is expensive, consider caching the result
538534

539535
# In order to make sure that the hash of a Fraction agrees
@@ -550,7 +546,8 @@ def __hash__(self):
550546
hash_ = _PyHASH_INF
551547
else:
552548
hash_ = abs(self._numerator) * dinv % _PyHASH_MODULUS
553-
return hash_ if self >= 0 else -hash_
549+
result = hash_ if self >= 0 else -hash_
550+
return -2 if result == -1 else result
554551

555552
def __eq__(a, b):
556553
"""a == b"""

Lib/test/test_fractions.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -546,6 +546,9 @@ def testHash(self):
546546
self.assertEquals(hash(2.5), hash(F(5, 2)))
547547
self.assertEquals(hash(10**50), hash(F(10**50)))
548548
self.assertNotEquals(hash(float(10**23)), hash(F(10**23)))
549+
# Check that __hash__ produces the same value as hash(), for
550+
# consistency with int and Decimal. (See issue #10356.)
551+
self.assertEquals(hash(F(-1)), F(-1).__hash__())
549552

550553
def testApproximatePi(self):
551554
# Algorithm borrowed from

Misc/NEWS

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,9 @@ Core and Builtins
6363
Library
6464
-------
6565

66+
- Fix Fraction.__hash__ so that Fraction.__hash__(-1) is -2. (See
67+
also issue #10356.)
68+
6669
- Issue #4471: Add the IMAP.starttls() method to enable encryption on
6770
standard IMAP4 connections. Original patch by Lorenzo M. Catucci.
6871

0 commit comments

Comments
 (0)