Skip to content

[backport to 2.7] bpo-28598: Support __rmod__ for RHS subclasses of str in % string formatting operations #382

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
[backport to 2.7] bpo-28598: Support __rmod__ for RHS subclasses of s…
…tr in % string formatting operations
  • Loading branch information
Martijn Pieters committed Mar 1, 2017
commit 9097de9e62f003bd038e4da6b36823a2d0b9853a
9 changes: 9 additions & 0 deletions Lib/test/test_str.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,15 @@ def test_formatting(self):
string_tests.MixinStrUnicodeUserStringTest.test_formatting(self)
self.assertRaises(OverflowError, '%c'.__mod__, 0x1234)

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")

@test_support.cpython_only
def test_formatting_huge_precision(self):
from _testcapi import INT_MAX
Expand Down
8 changes: 6 additions & 2 deletions Python/ceval.c
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy