-
-
Notifications
You must be signed in to change notification settings - Fork 32.1k
Improve conversions for fractions #88281
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
Currently, fraction.Fractions can be generated from floats via their as_integer_ratio method. This had been extended to also work with the Decimals class. It would be more generic - and IMHO more Pythonic - to just allow any data type, as long as it has an as_integer_ratio method. As an example, this allows numpy floats to be converted into fractions. |
Absolutely. I think that's a big part of the reason that as_integer_ratio is there. |
Note for posterity: I tried out pattern matching here but it was a little tricky and it slowed down the code a bit. At at least it worked. if denominator is None:
match numerator:
case int(x) if type(numerator) is int:
self._numerator = numerator
self._denominator = 1
return self
case numbers.Rational(numerator=numerator, denominator=denominator):
self._numerator = numerator
self._denominator = denominator
return self
case object(as_integer_ratio=_):
self._numerator, self._denominator = numerator.as_integer_ratio()
return self
case str(x):
m = _RATIONAL_FORMAT.match(numerator)
if m is None:
raise ValueError('Invalid literal for Fraction: %r' %
numerator)
numerator = int(m.group('num') or '0')
denom = m.group('denom')
if denom:
denominator = int(denom)
else:
denominator = 1
decimal = m.group('decimal')
if decimal:
scale = 10**len(decimal)
numerator = numerator * scale + int(decimal)
denominator *= scale
exp = m.group('exp')
if exp:
exp = int(exp)
if exp >= 0:
numerator *= 10**exp
else:
denominator *= 10**-exp
if m.group('sign') == '-':
numerator = -numerator
case _:
raise TypeError("argument should be a string "
"or a Rational instance") |
It was proposed before in bpo-37884. |
Accepting any object with |
Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.
Show more details
GitHub fields:
bugs.python.org fields:
The text was updated successfully, but these errors were encountered: