gh-119838: Treat Fraction as a real value in mixed arithmetic operations with complex (GH-119839)

This commit is contained in:
Serhiy Storchaka 2024-06-03 12:29:01 +03:00 committed by GitHub
parent 70934fb469
commit d7fcaa73b7
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 6 additions and 6 deletions

View File

@ -668,7 +668,7 @@ class Fraction(numbers.Rational):
elif isinstance(b, float): elif isinstance(b, float):
return fallback_operator(float(a), b) return fallback_operator(float(a), b)
elif handle_complex and isinstance(b, complex): elif handle_complex and isinstance(b, complex):
return fallback_operator(complex(a), b) return fallback_operator(float(a), b)
else: else:
return NotImplemented return NotImplemented
forward.__name__ = '__' + fallback_operator.__name__ + '__' forward.__name__ = '__' + fallback_operator.__name__ + '__'
@ -681,7 +681,7 @@ class Fraction(numbers.Rational):
elif isinstance(a, numbers.Real): elif isinstance(a, numbers.Real):
return fallback_operator(float(a), float(b)) return fallback_operator(float(a), float(b))
elif handle_complex and isinstance(a, numbers.Complex): elif handle_complex and isinstance(a, numbers.Complex):
return fallback_operator(complex(a), complex(b)) return fallback_operator(complex(a), float(b))
else: else:
return NotImplemented return NotImplemented
reverse.__name__ = '__r' + fallback_operator.__name__ + '__' reverse.__name__ = '__r' + fallback_operator.__name__ + '__'

View File

@ -806,10 +806,7 @@ class FractionTest(unittest.TestCase):
self.assertTypedEquals(F(3, 2) * Polar(4, 2), Polar(F(6, 1), 2)) self.assertTypedEquals(F(3, 2) * Polar(4, 2), Polar(F(6, 1), 2))
self.assertTypedEquals(F(3, 2) * Polar(4.0, 2), Polar(6.0, 2)) self.assertTypedEquals(F(3, 2) * Polar(4.0, 2), Polar(6.0, 2))
self.assertTypedEquals(F(3, 2) * Rect(4, 3), Rect(F(6, 1), F(9, 2))) self.assertTypedEquals(F(3, 2) * Rect(4, 3), Rect(F(6, 1), F(9, 2)))
with self.assertWarnsRegex(DeprecationWarning, self.assertTypedEquals(F(3, 2) * RectComplex(4, 3), RectComplex(6.0, 4.5))
"argument 'real' must be a real number, not complex"):
self.assertTypedEquals(F(3, 2) * RectComplex(4, 3),
RectComplex(6.0+0j, 4.5+0j))
self.assertRaises(TypeError, operator.mul, Polar(4, 2), F(3, 2)) self.assertRaises(TypeError, operator.mul, Polar(4, 2), F(3, 2))
self.assertTypedEquals(Rect(4, 3) * F(3, 2), 6.0 + 4.5j) self.assertTypedEquals(Rect(4, 3) * F(3, 2), 6.0 + 4.5j)
self.assertEqual(F(3, 2) * SymbolicComplex('X'), SymbolicComplex('3/2 * X')) self.assertEqual(F(3, 2) * SymbolicComplex('X'), SymbolicComplex('3/2 * X'))

View File

@ -0,0 +1,3 @@
In mixed arithmetic operations with :class:`~fractions.Fraction` and
complex, the fraction is now converted to :class:`float` instead of
:class:`complex`.