From b206e35bcc9536f7fcbc90710b6c336cb8872844 Mon Sep 17 00:00:00 2001 From: Tommy Beadle Date: Mon, 13 Jun 2016 11:31:04 -0400 Subject: [PATCH] Issue #27307 - Support index/attribute access for unnumbered fields in string.Formatter --- Lib/string.py | 4 ++-- Lib/test/test_string.py | 16 ++++++++++++++++ 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/Lib/string.py b/Lib/string.py index 7298c89..7469951 100644 --- a/Lib/string.py +++ b/Lib/string.py @@ -209,12 +209,12 @@ class Formatter: # the formatting # handle arg indexing when empty field_names are given. - if field_name == '': + if field_name == '' or field_name[0] in '[.': if auto_arg_index is False: raise ValueError('cannot switch from manual field ' 'specification to automatic field ' 'numbering') - field_name = str(auto_arg_index) + field_name = str(auto_arg_index) + field_name auto_arg_index += 1 elif field_name.isdigit(): if auto_arg_index: diff --git a/Lib/test/test_string.py b/Lib/test/test_string.py index 70439f8..75e3e4c 100644 --- a/Lib/test/test_string.py +++ b/Lib/test/test_string.py @@ -92,6 +92,9 @@ class ModuleTest(unittest.TestCase): self.assertEqual(fmt.format("{0.lumber}{0.jack}", x), 'lumberjack') with self.assertRaises(AttributeError): fmt.format("{0.lumber}{0.jack}", '') + self.assertEqual(fmt.format("{.lumber}{.jack}", x, x), 'lumberjack') + with self.assertRaises(AttributeError): + fmt.format("{.lumber}{.jack}", x, '') def test_index_lookup(self): fmt = string.Formatter() @@ -101,6 +104,19 @@ class ModuleTest(unittest.TestCase): fmt.format("{0[2]}{0[0]}", []) with self.assertRaises(KeyError): fmt.format("{0[2]}{0[0]}", {}) + self.assertEqual( + fmt.format("{[2]}{[0]}", lookup, lookup[1:]), + 'spamand' + ) + with self.assertRaises(IndexError): + fmt.format("{[0]}", []) + with self.assertRaises(KeyError): + fmt.format("{[0]}", {}) + lookup_dict = {'e': 'eggs'} + self.assertEqual( + fmt.format("{[2]}{[e]}", lookup, lookup_dict), + 'spameggs', + ) def test_override_get_value(self): class NamespaceFormatter(string.Formatter): -- 2.8.2