]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-72902: improve Fraction constructor speed for typical inputs (GH-134320)
authorSergey B Kirpichev <skirpichev@gmail.com>
Tue, 20 May 2025 09:47:27 +0000 (12:47 +0300)
committerGitHub <noreply@github.com>
Tue, 20 May 2025 09:47:27 +0000 (12:47 +0300)
This moves abc check for numbers.Rational - down.

Lib/fractions.py
Misc/NEWS.d/next/Library/2025-05-20-11-35-08.gh-issue-72902.jzEI-E.rst [new file with mode: 0644]

index 8163e3bb594f6beefb3acae7757a12be46980c2f..063f28478c73386b3a9d529ff3b428ca3e893fc2 100644 (file)
@@ -238,11 +238,6 @@ class Fraction(numbers.Rational):
                 self._denominator = 1
                 return self
 
-            elif isinstance(numerator, numbers.Rational):
-                self._numerator = numerator.numerator
-                self._denominator = numerator.denominator
-                return self
-
             elif (isinstance(numerator, float) or
                   (not isinstance(numerator, type) and
                    hasattr(numerator, 'as_integer_ratio'))):
@@ -278,6 +273,11 @@ class Fraction(numbers.Rational):
                 if m.group('sign') == '-':
                     numerator = -numerator
 
+            elif isinstance(numerator, numbers.Rational):
+                self._numerator = numerator.numerator
+                self._denominator = numerator.denominator
+                return self
+
             else:
                 raise TypeError("argument should be a string or a Rational "
                                 "instance or have the as_integer_ratio() method")
diff --git a/Misc/NEWS.d/next/Library/2025-05-20-11-35-08.gh-issue-72902.jzEI-E.rst b/Misc/NEWS.d/next/Library/2025-05-20-11-35-08.gh-issue-72902.jzEI-E.rst
new file mode 100644 (file)
index 0000000..932e751
--- /dev/null
@@ -0,0 +1,2 @@
+Improve speed (x1.1-1.8) of the :class:`~fractions.Fraction` constructor for
+typical inputs (:class:`float`'s, :class:`~decimal.Decimal`'s or strings).