Skip to content

Commit 62ff86f

Browse files
gh-130104: Call __rpow__ in ternary pow() if necessary (GH-130251)
Previously it was only called in binary pow() and the binary power operator.
1 parent 72da4a4 commit 62ff86f

File tree

10 files changed

+74
-18
lines changed

10 files changed

+74
-18
lines changed

Doc/reference/datamodel.rst

+9-4
Original file line numberDiff line numberDiff line change
@@ -3319,7 +3319,7 @@ left undefined.
33193319
:meth:`__divmod__` method should be the equivalent to using
33203320
:meth:`__floordiv__` and :meth:`__mod__`; it should not be related to
33213321
:meth:`__truediv__`. Note that :meth:`__pow__` should be defined to accept
3322-
an optional third argument if the ternary version of the built-in :func:`pow`
3322+
an optional third argument if the three-argument version of the built-in :func:`pow`
33233323
function is to be supported.
33243324

33253325
If one of those methods does not support the operation with the supplied
@@ -3356,10 +3356,15 @@ left undefined.
33563356
is called if ``type(x).__sub__(x, y)`` returns :data:`NotImplemented` or ``type(y)``
33573357
is a subclass of ``type(x)``. [#]_
33583358

3359-
.. index:: pair: built-in function; pow
3359+
Note that :meth:`__rpow__` should be defined to accept an optional third
3360+
argument if the three-argument version of the built-in :func:`pow` function
3361+
is to be supported.
33603362

3361-
Note that ternary :func:`pow` will not try calling :meth:`__rpow__` (the
3362-
coercion rules would become too complicated).
3363+
.. versionchanged:: next
3364+
3365+
Three-argument :func:`pow` now try calling :meth:`~object.__rpow__` if necessary.
3366+
Previously it was only called in two-argument :func:`!pow` and the binary
3367+
power operator.
33633368

33643369
.. note::
33653370

Doc/whatsnew/3.14.rst

+5
Original file line numberDiff line numberDiff line change
@@ -458,6 +458,11 @@ Other language changes
458458
The testbed can also be used to run the test suite of projects other than
459459
CPython itself. (Contributed by Russell Keith-Magee in :gh:`127592`.)
460460

461+
* Three-argument :func:`pow` now try calling :meth:`~object.__rpow__` if necessary.
462+
Previously it was only called in two-argument :func:`!pow` and the binary
463+
power operator.
464+
(Contributed by Serhiy Storchaka in :gh:`130104`.)
465+
461466
* Add a built-in implementation for HMAC (:rfc:`2104`) using formally verified
462467
code from the `HACL* <https://github.com/hacl-star/hacl-star/>`__ project.
463468
This implementation is used as a fallback when the OpenSSL implementation

Lib/_pydecimal.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -2440,12 +2440,12 @@ def __pow__(self, other, modulo=None, context=None):
24402440

24412441
return ans
24422442

2443-
def __rpow__(self, other, context=None):
2443+
def __rpow__(self, other, modulo=None, context=None):
24442444
"""Swaps self/other and returns __pow__."""
24452445
other = _convert_other(other)
24462446
if other is NotImplemented:
24472447
return other
2448-
return other.__pow__(self, context=context)
2448+
return other.__pow__(self, modulo, context=context)
24492449

24502450
def normalize(self, context=None):
24512451
"""Normalize- strip trailing 0s, change anything equal to 0 to 0e0"""

Lib/fractions.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -905,8 +905,10 @@ def __pow__(a, b, modulo=None):
905905
else:
906906
return NotImplemented
907907

908-
def __rpow__(b, a):
908+
def __rpow__(b, a, modulo=None):
909909
"""a ** b"""
910+
if modulo is not None:
911+
return NotImplemented
910912
if b._denominator == 1 and b._numerator >= 0:
911913
# If a is an int, keep it that way if possible.
912914
return a ** b._numerator

Lib/test/test_capi/test_number.py

+2-3
Original file line numberDiff line numberDiff line change
@@ -237,9 +237,8 @@ def __rpow__(*args):
237237
x = X()
238238
self.assertEqual(power(4, x), (x, 4))
239239
self.assertEqual(inplacepower(4, x), (x, 4))
240-
# XXX: Three-arg power doesn't use __rpow__.
241-
self.assertRaises(TypeError, power, 4, x, 5)
242-
self.assertRaises(TypeError, inplacepower, 4, x, 5)
240+
self.assertEqual(power(4, x, 5), (x, 4, 5))
241+
self.assertEqual(inplacepower(4, x, 5), (x, 4, 5))
243242

244243
class X:
245244
def __ipow__(*args):

Lib/test/test_decimal.py

+1-3
Original file line numberDiff line numberDiff line change
@@ -4493,12 +4493,10 @@ def test_implicit_context(self):
44934493
self.assertIs(Decimal("NaN").fma(7, 1).is_nan(), True)
44944494
# three arg power
44954495
self.assertEqual(pow(Decimal(10), 2, 7), 2)
4496+
self.assertEqual(pow(10, Decimal(2), 7), 2)
44964497
if self.decimal == C:
4497-
self.assertEqual(pow(10, Decimal(2), 7), 2)
44984498
self.assertEqual(pow(10, 2, Decimal(7)), 2)
44994499
else:
4500-
# XXX: Three-arg power doesn't use __rpow__.
4501-
self.assertRaises(TypeError, pow, 10, Decimal(2), 7)
45024500
# XXX: There is no special method to dispatch on the
45034501
# third arg of three-arg power.
45044502
self.assertRaises(TypeError, pow, 10, 2, Decimal(7))

Lib/test/test_descr.py

+4
Original file line numberDiff line numberDiff line change
@@ -3515,6 +3515,10 @@ def __rpow__(self, other, mod=None):
35153515
self.assertEqual(repr(2 ** I(3)), "I(8)")
35163516
self.assertEqual(repr(I(2) ** 3), "I(8)")
35173517
self.assertEqual(repr(pow(I(2), I(3), I(5))), "I(3)")
3518+
self.assertEqual(repr(pow(I(2), I(3), 5)), "I(3)")
3519+
self.assertEqual(repr(pow(I(2), 3, 5)), "I(3)")
3520+
self.assertEqual(repr(pow(2, I(3), 5)), "I(3)")
3521+
self.assertEqual(repr(pow(2, 3, I(5))), "3")
35183522
class S(str):
35193523
def __eq__(self, other):
35203524
return self.lower() == other.lower()

Lib/test/test_fractions.py

+6
Original file line numberDiff line numberDiff line change
@@ -1707,6 +1707,12 @@ def test_three_argument_pow(self):
17071707
self.assertRaisesMessage(TypeError,
17081708
message % ("Fraction", "int", "int"),
17091709
pow, F(3), 4, 5)
1710+
self.assertRaisesMessage(TypeError,
1711+
message % ("int", "Fraction", "int"),
1712+
pow, 3, F(4), 5)
1713+
self.assertRaisesMessage(TypeError,
1714+
message % ("int", "int", "Fraction"),
1715+
pow, 3, 4, F(5))
17101716

17111717

17121718
if __name__ == '__main__':
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
Three-argument :func:`pow` now try calling :meth:`~object.__rpow__` if
2+
necessary.
3+
Previously it was only called in two-argument :func:`!pow` and the binary
4+
power operator.

Objects/typeobject.c

+38-5
Original file line numberDiff line numberDiff line change
@@ -9992,13 +9992,46 @@ slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
99929992
{
99939993
if (modulus == Py_None)
99949994
return slot_nb_power_binary(self, other);
9995-
/* Three-arg power doesn't use __rpow__. But ternary_op
9996-
can call this when the second argument's type uses
9997-
slot_nb_power, so check before calling self.__pow__. */
9995+
9996+
/* The following code is a copy of SLOT1BINFULL, but for three arguments. */
9997+
PyObject* stack[3];
9998+
PyThreadState *tstate = _PyThreadState_GET();
9999+
int do_other = !Py_IS_TYPE(self, Py_TYPE(other)) &&
10000+
Py_TYPE(other)->tp_as_number != NULL &&
10001+
Py_TYPE(other)->tp_as_number->nb_power == slot_nb_power;
999810002
if (Py_TYPE(self)->tp_as_number != NULL &&
999910003
Py_TYPE(self)->tp_as_number->nb_power == slot_nb_power) {
10000-
PyObject* stack[3] = {self, other, modulus};
10001-
return vectorcall_method(&_Py_ID(__pow__), stack, 3);
10004+
PyObject *r;
10005+
if (do_other && PyType_IsSubtype(Py_TYPE(other), Py_TYPE(self))) {
10006+
int ok = method_is_overloaded(self, other, &_Py_ID(__rpow__));
10007+
if (ok < 0) {
10008+
return NULL;
10009+
}
10010+
if (ok) {
10011+
stack[0] = other;
10012+
stack[1] = self;
10013+
stack[2] = modulus;
10014+
r = vectorcall_maybe(tstate, &_Py_ID(__rpow__), stack, 3);
10015+
if (r != Py_NotImplemented)
10016+
return r;
10017+
Py_DECREF(r);
10018+
do_other = 0;
10019+
}
10020+
}
10021+
stack[0] = self;
10022+
stack[1] = other;
10023+
stack[2] = modulus;
10024+
r = vectorcall_maybe(tstate, &_Py_ID(__pow__), stack, 3);
10025+
if (r != Py_NotImplemented ||
10026+
Py_IS_TYPE(other, Py_TYPE(self)))
10027+
return r;
10028+
Py_DECREF(r);
10029+
}
10030+
if (do_other) {
10031+
stack[0] = other;
10032+
stack[1] = self;
10033+
stack[2] = modulus;
10034+
return vectorcall_maybe(tstate, &_Py_ID(__rpow__), stack, 3);
1000210035
}
1000310036
Py_RETURN_NOTIMPLEMENTED;
1000410037
}

0 commit comments

Comments
 (0)