[Python-checkins] gh-91851: Trivial optimizations in Fraction (#100791)

mdickinson webhook-mailer at python.org
Fri Jan 6 10:37:46 EST 2023


https://github.com/python/cpython/commit/0e640260dac2db081e56f52f8efb0e43e463ff2f
commit: 0e640260dac2db081e56f52f8efb0e43e463ff2f
branch: main
author: Sergey B Kirpichev <skirpichev at gmail.com>
committer: mdickinson <dickinsm at gmail.com>
date: 2023-01-06T15:37:34Z
summary:

gh-91851: Trivial optimizations in Fraction (#100791)

Make some trivial performance optimizations in Fraction

Uses private class attributes `_numerator` and `_denominator` in place of the `numerator` and `denominator` property accesses.

Co-authored-by: hauntsaninja <hauntsaninja at gmail.com>

files:
A Misc/NEWS.d/next/Library/2023-01-05-23-04-15.gh-issue-91851.AuCzU5.rst
M Lib/fractions.py

diff --git a/Lib/fractions.py b/Lib/fractions.py
index 4302f3f1b98d..939741115f91 100644
--- a/Lib/fractions.py
+++ b/Lib/fractions.py
@@ -650,12 +650,12 @@ def __trunc__(a):
 
     def __floor__(a):
         """math.floor(a)"""
-        return a.numerator // a.denominator
+        return a._numerator // a._denominator
 
     def __ceil__(a):
         """math.ceil(a)"""
         # The negations cleverly convince floordiv to return the ceiling.
-        return -(-a.numerator // a.denominator)
+        return -(-a._numerator // a._denominator)
 
     def __round__(self, ndigits=None):
         """round(self, ndigits)
@@ -663,10 +663,11 @@ def __round__(self, ndigits=None):
         Rounds half toward even.
         """
         if ndigits is None:
-            floor, remainder = divmod(self.numerator, self.denominator)
-            if remainder * 2 < self.denominator:
+            d = self._denominator
+            floor, remainder = divmod(self._numerator, d)
+            if remainder * 2 < d:
                 return floor
-            elif remainder * 2 > self.denominator:
+            elif remainder * 2 > d:
                 return floor + 1
             # Deal with the half case:
             elif floor % 2 == 0:
diff --git a/Misc/NEWS.d/next/Library/2023-01-05-23-04-15.gh-issue-91851.AuCzU5.rst b/Misc/NEWS.d/next/Library/2023-01-05-23-04-15.gh-issue-91851.AuCzU5.rst
new file mode 100644
index 000000000000..f427e8ae6791
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2023-01-05-23-04-15.gh-issue-91851.AuCzU5.rst
@@ -0,0 +1,3 @@
+Microoptimizations for :meth:`fractions.Fraction.__round__`,
+:meth:`fractions.Fraction.__ceil__` and
+:meth:`fractions.Fraction.__floor__`.



More information about the Python-checkins mailing list