From 7f8d9fcb0f311585207947ea052911c5589f5f92 Mon Sep 17 00:00:00 2001 From: Xiang Zhang Date: Wed, 1 Mar 2017 12:16:40 +0800 Subject: [PATCH] backport bpo-28598 --- Lib/test/test_str.py | 9 +++++++++ Misc/NEWS | 3 +++ Python/ceval.c | 8 ++++++-- 3 files changed, 18 insertions(+), 2 deletions(-) diff --git a/Lib/test/test_str.py b/Lib/test/test_str.py index 5bb9f4867bcb0e..8b306f4e8a4b0c 100644 --- a/Lib/test/test_str.py +++ b/Lib/test/test_str.py @@ -465,6 +465,15 @@ def test_startswith_endswith_errors(self): self.assertIn('str', exc) self.assertIn('tuple', exc) + def test_issue28598_strsubclass_rhs(self): + # A subclass of str with an __rmod__ method should be able to hook + # into the % operator + class SubclassedStr(str): + def __rmod__(self, other): + return 'Success, self.__rmod__({!r}) was called'.format(other) + self.assertEqual('lhs %% %r' % SubclassedStr('rhs'), + "Success, self.__rmod__('lhs %% %r') was called") + def test_main(): test_support.run_unittest(StrTest) diff --git a/Misc/NEWS b/Misc/NEWS index 4523df5a936155..407bf0fffe5220 100644 --- a/Misc/NEWS +++ b/Misc/NEWS @@ -10,6 +10,9 @@ What's New in Python 2.7.14? Core and Builtins ----------------- +- bpo-28598: Support __rmod__ for subclasses of str being called before + str.__mod__. Patch by Martijn Pieters. + - bpo-29602: Fix incorrect handling of signed zeros in complex constructor for complex subclasses and for inputs having a __complex__ method. Patch by Serhiy Storchaka. diff --git a/Python/ceval.c b/Python/ceval.c index 2af78ff8747411..733f0776ecfbcc 100644 --- a/Python/ceval.c +++ b/Python/ceval.c @@ -1446,10 +1446,14 @@ PyEval_EvalFrameEx(PyFrameObject *f, int throwflag) { w = POP(); v = TOP(); - if (PyString_CheckExact(v)) + if (PyString_CheckExact(v) + && (!PyString_Check(w) || PyString_CheckExact(w))) { + /* fast path; string formatting, but not if the RHS is a str subclass + (see issue28598) */ x = PyString_Format(v, w); - else + } else { x = PyNumber_Remainder(v, w); + } Py_DECREF(v); Py_DECREF(w); SET_TOP(x);