bpo-39985: Make string.Formatter with empty field name default to 0

This causes string.Formatter to behave like str.format in cases like
`"[0]".format((1, 2, 3))`, where `[0]` implicitly refers to the first
argument to `str.format`.
This commit is contained in:
Maxwell Bernstein 2020-03-18 16:47:24 -07:00
parent 3cde88439d
commit 93951a4a08
2 changed files with 6 additions and 0 deletions

View File

@ -222,8 +222,13 @@ class Formatter:
def get_value(self, key, args, kwargs):
if isinstance(key, int):
# "1234[x]"
return args[key]
elif key == "":
# "[x]"
return args[0]
else:
# "abcd[x]"
return kwargs[key]

View File

@ -96,6 +96,7 @@ class ModuleTest(unittest.TestCase):
fmt = string.Formatter()
lookup = ["eggs", "and", "spam"]
self.assertEqual(fmt.format("{0[2]}{0[0]}", lookup), 'spameggs')
self.assertEqual(fmt.format("{[2]}{1[0]}", lookup, (1, 2, 3)), 'spam1')
with self.assertRaises(IndexError):
fmt.format("{0[2]}{0[0]}", [])
with self.assertRaises(KeyError):