Skip to content

Commit 5075416

Browse files
bpo-30978: str.format_map() now passes key lookup exceptions through. (#2790)
Previously any exception was replaced with a KeyError exception.
1 parent 25e4f77 commit 5075416

File tree

4 files changed

+20
-7
lines changed

4 files changed

+20
-7
lines changed

Lib/test/test_re.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -468,7 +468,7 @@ def test_match_getitem(self):
468468
m[(0,)]
469469
with self.assertRaisesRegex(IndexError, 'no such group'):
470470
m[(0, 1)]
471-
with self.assertRaisesRegex(KeyError, 'a2'):
471+
with self.assertRaisesRegex(IndexError, 'no such group'):
472472
'a1={a2}'.format_map(m)
473473

474474
m = pat.match('ac')

Lib/test/test_unicode.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1278,6 +1278,13 @@ def __format__(self, spec):
12781278
self.assertRaises(ValueError, '{}'.format_map, 'a')
12791279
self.assertRaises(ValueError, '{a} {}'.format_map, {"a" : 2, "b" : 1})
12801280

1281+
class BadMapping:
1282+
def __getitem__(self, key):
1283+
return 1/0
1284+
self.assertRaises(KeyError, '{a}'.format_map, {})
1285+
self.assertRaises(TypeError, '{a}'.format_map, [])
1286+
self.assertRaises(ZeroDivisionError, '{a}'.format_map, BadMapping())
1287+
12811288
def test_format_huge_precision(self):
12821289
format_string = ".{}f".format(sys.maxsize + 1)
12831290
with self.assertRaises(ValueError):
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
str.format_map() now passes key lookup exceptions through.
2+
Previously any exception was replaced with a KeyError exception.

Objects/stringlib/unicode_format.h

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -410,18 +410,22 @@ get_field_object(SubString *input, PyObject *args, PyObject *kwargs,
410410
if (index == -1) {
411411
/* look up in kwargs */
412412
PyObject *key = SubString_new_object(&first);
413-
if (key == NULL)
413+
if (key == NULL) {
414414
goto error;
415-
416-
/* Use PyObject_GetItem instead of PyDict_GetItem because this
417-
code is no longer just used with kwargs. It might be passed
418-
a non-dict when called through format_map. */
419-
if ((kwargs == NULL) || (obj = PyObject_GetItem(kwargs, key)) == NULL) {
415+
}
416+
if (kwargs == NULL) {
420417
PyErr_SetObject(PyExc_KeyError, key);
421418
Py_DECREF(key);
422419
goto error;
423420
}
421+
/* Use PyObject_GetItem instead of PyDict_GetItem because this
422+
code is no longer just used with kwargs. It might be passed
423+
a non-dict when called through format_map. */
424+
obj = PyObject_GetItem(kwargs, key);
424425
Py_DECREF(key);
426+
if (obj == NULL) {
427+
goto error;
428+
}
425429
}
426430
else {
427431
/* If args is NULL, we have a format string with a positional field

0 commit comments

Comments
 (0)