Kaydet (Commit) b4f0e980 authored tarafından Xiang Zhang's avatar Xiang Zhang Kaydeden (comit) GitHub

bpo-28598: Support __rmod__ for RHS subclasses of str in % string formatting operations (GH-366)

üst 02eb4b0b
...@@ -465,6 +465,15 @@ class StrTest( ...@@ -465,6 +465,15 @@ class StrTest(
self.assertIn('str', exc) self.assertIn('str', exc)
self.assertIn('tuple', 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(): def test_main():
test_support.run_unittest(StrTest) test_support.run_unittest(StrTest)
......
...@@ -10,6 +10,9 @@ What's New in Python 2.7.14? ...@@ -10,6 +10,9 @@ What's New in Python 2.7.14?
Core and Builtins 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 - bpo-29602: Fix incorrect handling of signed zeros in complex constructor for
complex subclasses and for inputs having a __complex__ method. Patch complex subclasses and for inputs having a __complex__ method. Patch
by Serhiy Storchaka. by Serhiy Storchaka.
......
...@@ -1446,10 +1446,14 @@ PyEval_EvalFrameEx(PyFrameObject *f, int throwflag) ...@@ -1446,10 +1446,14 @@ PyEval_EvalFrameEx(PyFrameObject *f, int throwflag)
{ {
w = POP(); w = POP();
v = TOP(); 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); x = PyString_Format(v, w);
else } else {
x = PyNumber_Remainder(v, w); x = PyNumber_Remainder(v, w);
}
Py_DECREF(v); Py_DECREF(v);
Py_DECREF(w); Py_DECREF(w);
SET_TOP(x); SET_TOP(x);
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment