Skip to content
Closed
Show file tree
Hide file tree
Changes from 5 commits
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
4 changes: 4 additions & 0 deletions Lib/test/test_str.py
Original file line number Diff line number Diff line change
Expand Up @@ -1388,6 +1388,10 @@ def __repr__(self):
self.assertEqual("{!s}".format(n), 'N(data)')
self.assertRaises(TypeError, "{}".format, n)

# String index for sequences
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe you could delete this comment since the user won't see it anyway.

self.assertRaises(TypeError, "{[s]}".format, "abc")
self.assertRaises(TypeError, "{[-1]}".format, "abc")
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is something, that already fails with TypeError in the main. I think you should test actual error messages with assertRaises's msg argument or using assertRaisesRegex().


def test_format_map(self):
self.assertEqual(''.format_map({}), '')
self.assertEqual('a'.format_map({}), 'a')
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
More informative error message in :func:`str.format` when passing negative
integer or string index to sequence.
14 changes: 13 additions & 1 deletion Objects/stringlib/unicode_format.h
Original file line number Diff line number Diff line change
Expand Up @@ -462,8 +462,20 @@ get_field_object(SubString *input, PyObject *args, PyObject *kwargs,
tmp = getattr(obj, &name);
else
/* getitem lookup "[]" */
if (index == -1)
if (index == -1) {
if (PySequence_Check(obj)) {
/* string index can't be passed to sequence */
PyObject *str = SubString_new_object(&name);
if (str != NULL)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
if (str != NULL)
if (str)

Also beware PEP 7: "braces are required everywhere, even where C permits them to be omitted".

PyErr_Format(PyExc_TypeError,
"Index must be a sequence of digits, string %R "
"is not allowed",
str);
Py_XDECREF(str);
goto error;
}
tmp = getitem_str(obj, &name);
}
else
if (PySequence_Check(obj))
tmp = getitem_sequence(obj, index);
Expand Down
Loading