From eb19dce085de9723678acb8909b403a4c459c86a Mon Sep 17 00:00:00 2001 From: Florent Xicluna Date: Sat, 18 Sep 2010 23:34:07 +0000 Subject: [PATCH] Issue #1686: Fix string.Template when overriding the pattern attribute. --- Lib/string.py | 12 +++--------- Lib/test/test_pep292.py | 34 ++++++++++++++++++++++++++++++++++ Misc/NEWS | 2 ++ 3 files changed, 39 insertions(+), 9 deletions(-) diff --git a/Lib/string.py b/Lib/string.py index 2a450cd9628..d4fee391c1e 100644 --- a/Lib/string.py +++ b/Lib/string.py @@ -145,24 +145,18 @@ class Template(metaclass=_TemplateMetaclass): mapping = args[0] # Helper function for .sub() def convert(mo): - named = mo.group('named') + named = mo.group('named') or mo.group('braced') if named is not None: try: # We use this idiom instead of str() because the latter # will fail if val is a Unicode containing non-ASCII return '%s' % (mapping[named],) except KeyError: - return self.delimiter + named - braced = mo.group('braced') - if braced is not None: - try: - return '%s' % (mapping[braced],) - except KeyError: - return self.delimiter + '{' + braced + '}' + return mo.group() if mo.group('escaped') is not None: return self.delimiter if mo.group('invalid') is not None: - return self.delimiter + return mo.group() raise ValueError('Unrecognized named group in pattern', self.pattern) return self.pattern.sub(convert, self.template) diff --git a/Lib/test/test_pep292.py b/Lib/test/test_pep292.py index 8537b25616e..a9676495e97 100644 --- a/Lib/test/test_pep292.py +++ b/Lib/test/test_pep292.py @@ -125,6 +125,40 @@ class TestTemplate(unittest.TestCase): self.assertRaises(ValueError, s.substitute, {}) self.assertRaises(ValueError, s.safe_substitute, {}) + def test_braced_override(self): + class MyTemplate(Template): + pattern = r""" + \$(?: + (?P$) | + (?P[_a-z][_a-z0-9]*) | + @@(?P[_a-z][_a-z0-9]*)@@ | + (?P) | + ) + """ + + tmpl = 'PyCon in $@@location@@' + t = MyTemplate(tmpl) + self.assertRaises(KeyError, t.substitute, {}) + val = t.substitute({'location': 'Cleveland'}) + self.assertEqual(val, 'PyCon in Cleveland') + + def test_braced_override_safe(self): + class MyTemplate(Template): + pattern = r""" + \$(?: + (?P$) | + (?P[_a-z][_a-z0-9]*) | + @@(?P[_a-z][_a-z0-9]*)@@ | + (?P) | + ) + """ + + tmpl = 'PyCon in $@@location@@' + t = MyTemplate(tmpl) + self.assertEqual(t.safe_substitute(), tmpl) + val = t.safe_substitute({'location': 'Cleveland'}) + self.assertEqual(val, 'PyCon in Cleveland') + def test_unicode_values(self): s = Template('$who likes $what') d = dict(who='t\xffm', what='f\xfe\fed') diff --git a/Misc/NEWS b/Misc/NEWS index 34cea645f70..cdac64e4137 100644 --- a/Misc/NEWS +++ b/Misc/NEWS @@ -52,6 +52,8 @@ Core and Builtins Library ------- +- Issue #1686: Fix string.Template when overriding the pattern attribute. + - Issue #9854: SocketIO objects now observe the RawIOBase interface in non-blocking mode: they return None when an operation would block (instead of raising an exception).