Skip to content

Commit b4f0e98

Browse files
authored
bpo-28598: Support __rmod__ for RHS subclasses of str in % string formatting operations (GH-366)
1 parent 02eb4b0 commit b4f0e98

File tree

3 files changed

+18
-2
lines changed

3 files changed

+18
-2
lines changed

Lib/test/test_str.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -465,6 +465,15 @@ def test_startswith_endswith_errors(self):
465465
self.assertIn('str', exc)
466466
self.assertIn('tuple', exc)
467467

468+
def test_issue28598_strsubclass_rhs(self):
469+
# A subclass of str with an __rmod__ method should be able to hook
470+
# into the % operator
471+
class SubclassedStr(str):
472+
def __rmod__(self, other):
473+
return 'Success, self.__rmod__({!r}) was called'.format(other)
474+
self.assertEqual('lhs %% %r' % SubclassedStr('rhs'),
475+
"Success, self.__rmod__('lhs %% %r') was called")
476+
468477
def test_main():
469478
test_support.run_unittest(StrTest)
470479

Misc/NEWS

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,9 @@ What's New in Python 2.7.14?
1010
Core and Builtins
1111
-----------------
1212

13+
- bpo-28598: Support __rmod__ for subclasses of str being called before
14+
str.__mod__. Patch by Martijn Pieters.
15+
1316
- bpo-29602: Fix incorrect handling of signed zeros in complex constructor for
1417
complex subclasses and for inputs having a __complex__ method. Patch
1518
by Serhiy Storchaka.

Python/ceval.c

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1446,10 +1446,14 @@ PyEval_EvalFrameEx(PyFrameObject *f, int throwflag)
14461446
{
14471447
w = POP();
14481448
v = TOP();
1449-
if (PyString_CheckExact(v))
1449+
if (PyString_CheckExact(v)
1450+
&& (!PyString_Check(w) || PyString_CheckExact(w))) {
1451+
/* fast path; string formatting, but not if the RHS is a str subclass
1452+
(see issue28598) */
14501453
x = PyString_Format(v, w);
1451-
else
1454+
} else {
14521455
x = PyNumber_Remainder(v, w);
1456+
}
14531457
Py_DECREF(v);
14541458
Py_DECREF(w);
14551459
SET_TOP(x);

0 commit comments

Comments
 (0)