]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
bpo-28598: Support __rmod__ for RHS subclasses of str in % string formatting operatio...
authorXiang Zhang <angwerzx@126.com>
Wed, 1 Mar 2017 06:28:14 +0000 (14:28 +0800)
committerGitHub <noreply@github.com>
Wed, 1 Mar 2017 06:28:14 +0000 (14:28 +0800)
Lib/test/test_str.py
Misc/NEWS
Python/ceval.c

index 5bb9f4867bcb0e888910c5eedfc0849840d3557f..8b306f4e8a4b0cfa16badd1b7152342dcc9d7cbb 100644 (file)
@@ -465,6 +465,15 @@ class StrTest(
             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)
 
index 4523df5a93615555db0f07116a096d35c9693763..407bf0fffe52201d82b08ca01c1a6f77d131f1e0 100644 (file)
--- 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.
index 2af78ff874741103459fb07f32d6cc2015cf566e..733f0776ecfbcc637593eb0bdc62b4f54901a951 100644 (file)
@@ -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);