[bindings/python] Keep operand order in reflected GncNumeric operators

The reflected operators swapped their operands, so an int or float on
the left of a GncNumeric gave the wrong answer for the non-commutative
operations: 10 - GncNumeric(3) returned -7 and 10 / GncNumeric(4)
returned 2/5. Convert the left-hand operand and keep it on the left.
This commit is contained in:
Ryan Duguid committed 2026-10-30 08:55:57 +11:00
1 parent 1283b34811
commit 65949b43f0
2 files changed
+12 -1

No files matched your search

+2 -1
View File
@@ -625,8 +625,9 @@ class GncNumeric(GnuCashCoreClass):
forward.__doc__ = monomorphic_operator.__doc__
def reverse(b, a):
# b is self, the right-hand operand; a is the left-hand one.
if isinstance(a, (GncNumeric, int, float)):
return forward(b, a)
return forward(GncNumeric(a), b)
else:
return NotImplemented
reverse.__name__ = '__r' + fallback_operator.__name__ + '__'
+10
View File
@@ -85,6 +85,16 @@ class TestGncNumeric(TestCase):
self.assertEqual(fraction.numerator, 1000)
self.assertEqual(fraction.denominator, 3)
def test_reflected_operators(self):
# A plain number on the left must stay the left-hand operand.
self.assertEqual(10 - GncNumeric(3), GncNumeric(7))
self.assertEqual(1.5 - GncNumeric(1, 2), GncNumeric(1))
self.assertEqual(10 / GncNumeric(4), GncNumeric(5, 2))
self.assertEqual(1 / GncNumeric(3), GncNumeric(1, 3))
self.assertEqual(7 // GncNumeric(2), GncNumeric(3))
self.assertEqual(10 + GncNumeric(3), GncNumeric(13))
self.assertEqual(10 * GncNumeric(3), GncNumeric(30))
def test_incorect_args(self):
with self.assertRaises(TypeError):
GncNumeric(1, 2, 3)