Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit da2c7eb

Browse files
committed
allow any type with __getitem__ to be a mapping for the purposes of % (python#15801)
1 parent 7e2f197 commit da2c7eb

4 files changed

Lines changed: 15 additions & 4 deletions

File tree

Lib/test/string_tests.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1130,6 +1130,10 @@ def test_formatting(self):
11301130

11311131
class X(object): pass
11321132
self.checkraises(TypeError, 'abc', '__mod__', X())
1133+
class X(Exception):
1134+
def __getitem__(self, k):
1135+
return k
1136+
self.checkequal('melon apple', '%(melon)s %(apple)s', '__mod__', X())
11331137

11341138
def test_floatformatting(self):
11351139
# float formatting

Misc/NEWS

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,13 @@ What's New in Python 2.7.4?
66

77
*Release date: XXXX-XX-XX*
88

9+
Core and Builtins
10+
-----------------
11+
12+
- Issue #15801 (again): With string % formatting, relax the type check for a
13+
mapping such that any type with a __getitem__ can be used on the right hand
14+
side.
15+
916
Library
1017
-------
1118

Objects/stringobject.c

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4257,8 +4257,8 @@ PyString_Format(PyObject *format, PyObject *args)
42574257
arglen = -1;
42584258
argidx = -2;
42594259
}
4260-
if (PyMapping_Check(args) && !PyTuple_Check(args) &&
4261-
!PyObject_TypeCheck(args, &PyBaseString_Type))
4260+
if (Py_TYPE(args)->tp_as_mapping && Py_TYPE(args)->tp_as_mapping->mp_subscript &&
4261+
!PyTuple_Check(args) && !PyObject_TypeCheck(args, &PyBaseString_Type))
42624262
dict = args;
42634263
while (--fmtcnt >= 0) {
42644264
if (*fmt != '%') {

Objects/unicodeobject.c

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8287,8 +8287,8 @@ PyObject *PyUnicode_Format(PyObject *format,
82878287
arglen = -1;
82888288
argidx = -2;
82898289
}
8290-
if (PyMapping_Check(args) && !PyTuple_Check(args) &&
8291-
!PyObject_TypeCheck(args, &PyBaseString_Type))
8290+
if (Py_TYPE(args)->tp_as_mapping && Py_TYPE(args)->tp_as_mapping->mp_subscript &&
8291+
!PyTuple_Check(args) && !PyObject_TypeCheck(args, &PyBaseString_Type))
82928292
dict = args;
82938293

82948294
while (--fmtcnt >= 0) {

0 commit comments

Comments
 (0)