From 0e640260dac2db081e56f52f8efb0e43e463ff2f Mon Sep 17 00:00:00 2001 From: Sergey B Kirpichev Date: Fri, 6 Jan 2023 18:37:34 +0300 Subject: 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 --- Lib/fractions.py | 11 ++++++----- .../Library/2023-01-05-23-04-15.gh-issue-91851.AuCzU5.rst | 3 +++ 2 files changed, 9 insertions(+), 5 deletions(-) create mode 100644 Misc/NEWS.d/next/Library/2023-01-05-23-04-15.gh-issue-91851.AuCzU5.rst diff --git a/Lib/fractions.py b/Lib/fractions.py index 4302f3f..9397411 100644 --- a/Lib/fractions.py +++ b/Lib/fractions.py @@ -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 index 0000000..f427e8a --- /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__`. -- cgit v0.12