diff options
author | Serhiy Storchaka <storchaka@gmail.com> | 2024-07-19 05:06:53 (GMT) |
---|---|---|
committer | GitHub <noreply@github.com> | 2024-07-19 05:06:53 (GMT) |
commit | c8d2630995fc234f8276e35643a4a43e62224510 (patch) | |
tree | 359d25600fe9da975fdc9ee45dbba022bb7c5978 /Lib/fractions.py | |
parent | eaf094c09b5b1c33435c60ef49b1cec78c32573c (diff) | |
download | cpython-c8d2630995fc234f8276e35643a4a43e62224510.zip cpython-c8d2630995fc234f8276e35643a4a43e62224510.tar.gz cpython-c8d2630995fc234f8276e35643a4a43e62224510.tar.bz2 |
gh-82017: Support as_integer_ratio() in the Fraction constructor (GH-120271)
Any objects that have the as_integer_ratio() method (e.g. numpy.float128)
can now be converted to a fraction.
Diffstat (limited to 'Lib/fractions.py')
-rw-r--r-- | Lib/fractions.py | 8 |
1 files changed, 4 insertions, 4 deletions
diff --git a/Lib/fractions.py b/Lib/fractions.py index 5655039..34fd080 100644 --- a/Lib/fractions.py +++ b/Lib/fractions.py @@ -3,7 +3,6 @@ """Fraction, infinite-precision, rational numbers.""" -from decimal import Decimal import functools import math import numbers @@ -244,7 +243,9 @@ class Fraction(numbers.Rational): self._denominator = numerator.denominator return self - elif isinstance(numerator, (float, Decimal)): + elif (isinstance(numerator, float) or + (not isinstance(numerator, type) and + hasattr(numerator, 'as_integer_ratio'))): # Exact conversion self._numerator, self._denominator = numerator.as_integer_ratio() return self @@ -278,8 +279,7 @@ class Fraction(numbers.Rational): numerator = -numerator else: - raise TypeError("argument should be a string " - "or a Rational instance") + raise TypeError("argument should be a string or a number") elif type(numerator) is int is type(denominator): pass # *very* normal case |