From 8f2c34fceef1d54e7273de937561e03b74372a5d Mon Sep 17 00:00:00 2001 From: Mathieu Dupuy Date: Thu, 3 Dec 2026 01:24:53 +0100 Subject: [PATCH] Fall back to the forward operator if a reverse one returns NotImplemented When the reverse operator takes precedence, because the right operand is a subclass of the left one or the left one is a sequence, the forward operator was discarded, so that returning NotImplemented from the reverse operator resulted in TypeError. Try the forward operator after it instead. Co-Authored-By: Claude Sonnet 5.5 --- .../Binding/PythonProtocol.Operations.cs | 55 +++++++++++++------ tests/suite/test_class.py | 35 ++++++++++++ 2 files changed, 74 insertions(+), 16 deletions(-) diff --git a/src/core/IronPython/Runtime/Binding/PythonProtocol.Operations.cs b/src/core/IronPython/Runtime/Binding/PythonProtocol.Operations.cs index 5bdad3a51..aaf35d5e6 100644 --- a/src/core/IronPython/Runtime/Binding/PythonProtocol.Operations.cs +++ b/src/core/IronPython/Runtime/Binding/PythonProtocol.Operations.cs @@ -689,12 +689,12 @@ private static NewExpression MakeEnumeratorResult(Expression tmp) { SlotOrFunction rbinder; PythonTypeSlot fSlot; PythonTypeSlot rSlot; - GetOperatorMethods(types, operation, PythonContext.GetPythonContext(binder), out fbinder, out rbinder, out fSlot, out rSlot); + GetOperatorMethods(types, operation, PythonContext.GetPythonContext(binder), out fbinder, out rbinder, out fSlot, out rSlot, out bool reverseFirst); - return MakeBinaryOperatorResult(types, binder, operation, fbinder, rbinder, fSlot, rSlot, errorSuggestion); + return MakeBinaryOperatorResult(types, binder, operation, fbinder, rbinder, fSlot, rSlot, reverseFirst, errorSuggestion); } - private static void GetOperatorMethods(DynamicMetaObject/*!*/[]/*!*/ types, PythonOperationKind oper, PythonContext state, out SlotOrFunction fbinder, out SlotOrFunction rbinder, out PythonTypeSlot fSlot, out PythonTypeSlot rSlot) { + private static void GetOperatorMethods(DynamicMetaObject/*!*/[]/*!*/ types, PythonOperationKind oper, PythonContext state, out SlotOrFunction fbinder, out SlotOrFunction rbinder, out PythonTypeSlot fSlot, out PythonTypeSlot rSlot, out bool reverseFirst) { oper &= ~PythonOperationKind.InPlace; string op, rop; @@ -759,17 +759,29 @@ private static void GetOperatorMethods(DynamicMetaObject/*!*/[]/*!*/ types, Pyth } } - // TODO: this is incorrect - if the rslot returns NotImplemented then fslot is never called and a TypeError will be raised (https://github.com/IronLanguages/ironpython3/issues/1479) - if (fParent != null && (rbinder.Success || rSlot != null) && rParent != fParent && rParent.IsSubclassOf(fParent)) { - // Python says if x + subx and subx defines __r*__ we should call r*. - fbinder = SlotOrFunction.Empty; - fSlot = null; - } + // The reverse operator is tried before the forward one: + // - Python says if x + subx and subx defines __r*__ we should call r*. + // - if the left operand is a sequence and the right operand defines __radd__, we should call __radd__. + // The forward operator is still used if the reverse one returns NotImplemented. + reverseFirst = fParent != null && (rbinder.Success || rSlot != null) && rParent != fParent && + (rParent.IsSubclassOf(fParent) || (oper == PythonOperationKind.Add && isSequence)); - // TODO: this is incorrect - if the rslot returns NotImplemented then fslot is never called and a TypeError will be raised (https://github.com/IronLanguages/ironpython3/issues/560) - if (oper == PythonOperationKind.Add && fParent != null && (rbinder.Success || rSlot != null) && rParent != fParent && isSequence) { - // if the left operand is a sequence and the right operand defines __radd__, we should call __radd__. - fbinder = SlotOrFunction.Empty; + if (rSlot != null && types[0].GetLimitType() == typeof(int) && typeof(Extensible).IsAssignableFrom(types[1].GetLimitType())) { + // The operators of Int32 do not accept subclasses of int, which are normally handled by the + // reverse operator that the subclass inherits. If the subclass overrides it, call the override + // first and fall back to the forward operator applied to both values as BigInteger. + reverseFirst = true; + DynamicMetaObject[] values = { + new DynamicMetaObject( + AstUtils.Convert(AstUtils.Convert(types[0].Expression, typeof(int)), typeof(BigInteger)), + BindingRestrictions.Empty + ), + new DynamicMetaObject( + Ast.Property(AstUtils.Convert(types[1].Expression, typeof(Extensible)), nameof(Extensible.Value)), + BindingRestrictions.Empty + ), + }; + SlotOrFunction.TryGetBinder(state, values, op, null, out fbinder, out _); fSlot = null; } } @@ -790,7 +802,7 @@ private static bool IsSequence(DynamicMetaObject/*!*/ metaObject) { return false; } - private static DynamicMetaObject/*!*/ MakeBinaryOperatorResult(DynamicMetaObject/*!*/[]/*!*/ types, DynamicMetaObjectBinder/*!*/ operation, PythonOperationKind op, SlotOrFunction/*!*/ fCand, SlotOrFunction/*!*/ rCand, PythonTypeSlot fSlot, PythonTypeSlot rSlot, DynamicMetaObject errorSuggestion) { + private static DynamicMetaObject/*!*/ MakeBinaryOperatorResult(DynamicMetaObject/*!*/[]/*!*/ types, DynamicMetaObjectBinder/*!*/ operation, PythonOperationKind op, SlotOrFunction/*!*/ fCand, SlotOrFunction/*!*/ rCand, PythonTypeSlot fSlot, PythonTypeSlot rSlot, bool reverseFirst, DynamicMetaObject errorSuggestion) { Assert.NotNull(operation, fCand, rCand); SlotOrFunction fTarget, rTarget; @@ -809,14 +821,25 @@ private static bool IsSequence(DynamicMetaObject/*!*/ metaObject) { } } - if (!SlotOrFunction.GetCombinedTargets(fCand, rCand, out fTarget, out rTarget) && + bool hasTargets = SlotOrFunction.GetCombinedTargets(fCand, rCand, out fTarget, out rTarget); + if (reverseFirst && fCand.Success) { + // the forward operator is only a fallback, so keep it even if it requires more conversions + fTarget = fCand; + } + + if (!hasTargets && fSlot == null && rSlot == null && bodyBuilder.NoConditions) { return MakeRuleForNoMatch(operation, op, errorSuggestion, types); } - if (MakeOneTarget(PythonContext.GetPythonContext(operation), fTarget, fSlot, bodyBuilder, false, types)) { + if (reverseFirst) { + if (MakeOneTarget(state, rTarget, rSlot, bodyBuilder, true, types) && + MakeOneTarget(state, fTarget, fSlot, bodyBuilder, false, types)) { + bodyBuilder.FinishCondition(MakeBinaryThrow(operation, op, types).Expression, typeof(object)); + } + } else if (MakeOneTarget(PythonContext.GetPythonContext(operation), fTarget, fSlot, bodyBuilder, false, types)) { if (rSlot != null) { MakeSlotCall(PythonContext.GetPythonContext(operation), types, bodyBuilder, rSlot, true); bodyBuilder.FinishCondition(MakeBinaryThrow(operation, op, types).Expression, typeof(object)); diff --git a/tests/suite/test_class.py b/tests/suite/test_class.py index cf91b55ca..eb29c023a 100644 --- a/tests/suite/test_class.py +++ b/tests/suite/test_class.py @@ -3268,6 +3268,41 @@ class C: self.assertEqual(C.b, 10) self.assertEqual(x, 10) + def test_reverse_operator_returning_not_implemented(self): + # https://github.com/IronLanguages/ironpython3/issues/1479 + import operator + calls = [] + def subclass(base, name): + def method(self, other): + calls.append(name) + return NotImplemented + return type('sub', (base,), {name: method}) + + operators = ('add', 'sub', 'mul', 'truediv', 'floordiv', 'mod', 'pow', 'and_', 'or_', 'xor', 'lshift', 'rshift') + for name in operators: + op = getattr(operator, name) + sub = subclass(int, '__r%s__' % name.rstrip('_')) + for left in (6, 2**70): + del calls[:] + self.assertEqual(op(left, sub(2)), op(left, 2)) + self.assertEqual(len(calls), 1) # the reverse operator is tried first + + for name in ('add', 'sub', 'mul', 'truediv'): + sub = subclass(float, '__r%s__' % name) + self.assertEqual(getattr(operator, name)(6.0, sub(2.0)), getattr(operator, name)(6.0, 2.0)) + + for left, right in (([1], [2]), ((1,), (2,)), (b'a', b'b')): + del calls[:] + self.assertEqual(left + subclass(type(right), '__radd__')(right), left + right) + self.assertEqual(calls, ['__radd__']) + + # nothing to fall back to + class R: + def __radd__(self, other): return NotImplemented + for left in (1, 'a', [1], (), R()): + with self.assertRaises(TypeError): + left + R() + def test_private_names_in_fstrings(self): # https://github.com/IronLanguages/ironpython3/issues/1421 class C: