Skip to content

Commit 0e64026

Browse files
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 <[email protected]>
1 parent 15c4478 commit 0e64026

File tree

2 files changed

+9
-5
lines changed

2 files changed

+9
-5
lines changed

Lib/fractions.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -650,23 +650,24 @@ def __trunc__(a):
650650

651651
def __floor__(a):
652652
"""math.floor(a)"""
653-
return a.numerator // a.denominator
653+
return a._numerator // a._denominator
654654

655655
def __ceil__(a):
656656
"""math.ceil(a)"""
657657
# The negations cleverly convince floordiv to return the ceiling.
658-
return -(-a.numerator // a.denominator)
658+
return -(-a._numerator // a._denominator)
659659

660660
def __round__(self, ndigits=None):
661661
"""round(self, ndigits)
662662
663663
Rounds half toward even.
664664
"""
665665
if ndigits is None:
666-
floor, remainder = divmod(self.numerator, self.denominator)
667-
if remainder * 2 < self.denominator:
666+
d = self._denominator
667+
floor, remainder = divmod(self._numerator, d)
668+
if remainder * 2 < d:
668669
return floor
669-
elif remainder * 2 > self.denominator:
670+
elif remainder * 2 > d:
670671
return floor + 1
671672
# Deal with the half case:
672673
elif floor % 2 == 0:
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Microoptimizations for :meth:`fractions.Fraction.__round__`,
2+
:meth:`fractions.Fraction.__ceil__` and
3+
:meth:`fractions.Fraction.__floor__`.

0 commit comments

Comments
 (0)