Skip to content

Commit caa608f

Browse files
committed
gh-72902: speedup Fraction.from_Decimal/float in typical cases
1 parent fe3c7e1 commit caa608f

File tree

2 files changed

+13
-10
lines changed

2 files changed

+13
-10
lines changed

Lib/fractions.py

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -335,23 +335,23 @@ def from_float(cls, f):
335335
Beware that Fraction.from_float(0.3) != Fraction(3, 10).
336336
337337
"""
338-
if isinstance(f, numbers.Integral):
338+
if not isinstance(f, float):
339+
if not isinstance(f, numbers.Integral):
340+
raise TypeError("%s.from_float() only takes floats, not %r (%s)" %
341+
(cls.__name__, f, type(f).__name__))
339342
return cls(f)
340-
elif not isinstance(f, float):
341-
raise TypeError("%s.from_float() only takes floats, not %r (%s)" %
342-
(cls.__name__, f, type(f).__name__))
343343
return cls._from_coprime_ints(*f.as_integer_ratio())
344344

345345
@classmethod
346346
def from_decimal(cls, dec):
347347
"""Converts a finite Decimal instance to a rational number, exactly."""
348348
from decimal import Decimal
349-
if isinstance(dec, numbers.Integral):
350-
dec = Decimal(int(dec))
351-
elif not isinstance(dec, Decimal):
352-
raise TypeError(
353-
"%s.from_decimal() only takes Decimals, not %r (%s)" %
354-
(cls.__name__, dec, type(dec).__name__))
349+
if not isinstance(dec, Decimal):
350+
if not isinstance(dec, numbers.Integral):
351+
raise TypeError(
352+
"%s.from_decimal() only takes Decimals, not %r (%s)" %
353+
(cls.__name__, dec, type(dec).__name__))
354+
dec = int(dec)
355355
return cls._from_coprime_ints(*dec.as_integer_ratio())
356356

357357
@classmethod
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Optimize (~x1.40-50 speedup) :meth:`fractions.Fraction.from_Decimal` and
2+
:meth:`fractions.Fraction.from_float` for :class:`~decimal.Decimal` and
3+
:class:`float` inputs, respectively. Patch by Sergey B Kirpichev.

0 commit comments

Comments
 (0)