Skip to content
Projects
Groups
Snippets
Help
Loading...
Help
Support
Keyboard shortcuts
?
Submit feedback
Contribute to GitLab
Sign in / Register
Toggle navigation
C
cpython
Project overview
Project overview
Details
Activity
Releases
Repository
Repository
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Issues
0
Issues
0
List
Boards
Labels
Milestones
Merge Requests
0
Merge Requests
0
Analytics
Analytics
Repository
Value Stream
Wiki
Wiki
Members
Members
Collapse sidebar
Close sidebar
Activity
Graph
Create a new issue
Commits
Issue Boards
Open sidebar
Kirill Smelkov
cpython
Commits
f3cb68f2
Commit
f3cb68f2
authored
Aug 15, 2019
by
Raymond Hettinger
Committed by
GitHub
Aug 15, 2019
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
bpo-37863: Optimize Fraction.__hash__() (#15298)
parent
69f37bcb
Changes
2
Hide whitespace changes
Inline
Side-by-side
Showing
2 changed files
with
12 additions
and
15 deletions
+12
-15
Lib/fractions.py
Lib/fractions.py
+11
-15
Misc/NEWS.d/next/Library/2019-08-14-20-46-39.bpo-37863.CkXqgX.rst
...S.d/next/Library/2019-08-14-20-46-39.bpo-37863.CkXqgX.rst
+1
-0
No files found.
Lib/fractions.py
View file @
f3cb68f2
...
...
@@ -556,23 +556,19 @@ class Fraction(numbers.Rational):
def
__hash__
(
self
):
"""hash(self)"""
# XXX since this method is expensive, consider caching the result
# In order to make sure that the hash of a Fraction agrees
# with the hash of a numerically equal integer, float or
# Decimal instance, we follow the rules for numeric hashes
# outlined in the documentation. (See library docs, 'Built-in
# Types').
# dinv is the inverse of self._denominator modulo the prime
# _PyHASH_MODULUS, or 0 if self._denominator is divisible by
# _PyHASH_MODULUS.
dinv
=
pow
(
self
.
_denominator
,
_PyHASH_MODULUS
-
2
,
_PyHASH_MODULUS
)
if
not
dinv
:
# To make sure that the hash of a Fraction agrees with the hash
# of a numerically equal integer, float or Decimal instance, we
# follow the rules for numeric hashes outlined in the
# documentation. (See library docs, 'Built-in Types').
try
:
dinv
=
pow
(
self
.
_denominator
,
-
1
,
_PyHASH_MODULUS
)
except
ValueError
:
# ValueError means there is no modular inverse
hash_
=
_PyHASH_INF
else
:
hash_
=
abs
(
self
.
_numerator
)
*
dinv
%
_PyHASH_MODULUS
result
=
hash_
if
self
>=
0
else
-
hash_
hash_
=
hash
(
abs
(
self
.
_numerator
)
)
*
dinv
%
_PyHASH_MODULUS
result
=
hash_
if
self
.
_numerator
>=
0
else
-
hash_
return
-
2
if
result
==
-
1
else
result
def
__eq__
(
a
,
b
):
...
...
Misc/NEWS.d/next/Library/2019-08-14-20-46-39.bpo-37863.CkXqgX.rst
0 → 100644
View file @
f3cb68f2
Optimizations for Fraction.__hash__ suggested by Tim Peters.
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment