]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-91851: Trivial optimizations in Fraction (#100791)
authorSergey B Kirpichev <skirpichev@gmail.com>
Fri, 6 Jan 2023 15:37:34 +0000 (18:37 +0300)
committerGitHub <noreply@github.com>
Fri, 6 Jan 2023 15:37:34 +0000 (15:37 +0000)
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@gmail.com>
Lib/fractions.py
Misc/NEWS.d/next/Library/2023-01-05-23-04-15.gh-issue-91851.AuCzU5.rst [new file with mode: 0644]

index 4302f3f1b98deab10e3f10385c921aeb0149f768..939741115f91921486f794c6c1aa1b5621f7bd3c 100644 (file)
@@ -650,12 +650,12 @@ class Fraction(numbers.Rational):
 
     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 @@ class Fraction(numbers.Rational):
         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 (file)
index 0000000..f427e8a
--- /dev/null
@@ -0,0 +1,3 @@
+Microoptimizations for :meth:`fractions.Fraction.__round__`,
+:meth:`fractions.Fraction.__ceil__` and
+:meth:`fractions.Fraction.__floor__`.