From: Sergey B Kirpichev Date: Fri, 6 Jan 2023 15:37:34 +0000 (+0300) Subject: gh-91851: Trivial optimizations in Fraction (#100791) X-Git-Tag: v3.12.0a4~41 X-Git-Url: http://git.ipfire.org/gitweb.cgi?a=commitdiff_plain;h=0e640260dac2db081e56f52f8efb0e43e463ff2f;p=thirdparty%2FPython%2Fcpython.git 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 --- 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 @@ 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 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__`.