Skip to content

Commit e80bb26

Browse files
committed
bpo-46307: Add string.Template.is_valid method
1 parent b14f8bc commit e80bb26

File tree

4 files changed

+71
-10
lines changed

4 files changed

+71
-10
lines changed

Doc/library/string.rst

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -783,6 +783,18 @@ these rules. The methods of :class:`Template` are:
783783
templates containing dangling delimiters, unmatched braces, or
784784
placeholders that are not valid Python identifiers.
785785

786+
787+
.. method:: is_valid()
788+
789+
Returns false if the template has invalid placeholders that will cause
790+
:meth:`substitute` to raise :exc:`ValueError`.
791+
792+
793+
.. method:: get_identifiers()
794+
795+
Returns a list of the valid identifiers in the template, in the order
796+
they first appear, ignoring any invalid identifiers.
797+
786798
:class:`Template` instances also provide one public data attribute:
787799

788800
.. attribute:: template

Lib/string.py

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -141,14 +141,33 @@ def convert(mo):
141141
self.pattern)
142142
return self.pattern.sub(convert, self.template)
143143

144-
def get_identifiers(self, *, raise_on_invalid=True):
144+
def is_valid(self):
145+
for mo in self.pattern.finditer(self.template):
146+
if mo.group('invalid') is not None:
147+
return False
148+
if (mo.group('named') is None
149+
and mo.group('braced') is None
150+
and mo.group('escaped') is None):
151+
# If all the groups are None, there must be
152+
# another group we're not expecting
153+
raise ValueError('Unrecognized named group in pattern',
154+
self.pattern)
155+
return True
156+
157+
def get_identifiers(self):
145158
ids = []
146159
for mo in self.pattern.finditer(self.template):
147160
named = mo.group('named') or mo.group('braced')
148161
if named is not None and named not in ids:
162+
# add a named group only the first time it appears
149163
ids.append(named)
150-
elif mo.group('invalid') is not None and raise_on_invalid:
151-
self._invalid(mo)
164+
elif (named is None
165+
and mo.group('invalid') is None
166+
and mo.group('escaped') is None):
167+
# If all the groups are None, there must be
168+
# another group we're not expecting
169+
raise ValueError('Unrecognized named group in pattern',
170+
self.pattern)
152171
return ids
153172

154173
# Initialize Template.pattern. __init_subclass__() is automatically called

Lib/test/test_string.py

Lines changed: 36 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -475,6 +475,27 @@ class PieDelims(Template):
475475
self.assertEqual(s.substitute(dict(who='tim', what='ham')),
476476
'tim likes to eat a bag of ham worth $100')
477477

478+
def test_is_valid(self):
479+
eq = self.assertEqual
480+
s = Template('$who likes to eat a bag of ${what} worth $$100')
481+
self.assertTrue(s.is_valid())
482+
483+
s = Template('$who likes to eat a bag of ${what} worth $100')
484+
self.assertFalse(s.is_valid())
485+
486+
# if the pattern has an unrecognized capture group,
487+
# it should raise ValueError like substitute and safe_substitute do
488+
class BadPattern(Template):
489+
pattern = r"""
490+
(?P<badname>.*) |
491+
(?P<escaped>@{2}) |
492+
@(?P<named>[_a-z][._a-z0-9]*) |
493+
@{(?P<braced>[_a-z][._a-z0-9]*)} |
494+
(?P<invalid>@) |
495+
"""
496+
s = BadPattern('@bag.foo.who likes to eat a bag of @bag.what')
497+
self.assertRaises(ValueError, s.is_valid)
498+
478499
def test_get_identifiers(self):
479500
eq = self.assertEqual
480501
raises = self.assertRaises
@@ -487,15 +508,24 @@ def test_get_identifiers(self):
487508
ids = s.get_identifiers()
488509
eq(ids, ['who', 'what'])
489510

490-
# invalid identifiers are raised
491-
s = Template('$who likes to eat a bag of ${what} worth $100')
492-
raises(ValueError, s.get_identifiers)
493-
494-
# invalid identifiers are ignored with raise_on_invalid=False
511+
# invalid identifiers are ignored
495512
s = Template('$who likes to eat a bag of ${what} worth $100')
496-
ids = s.get_identifiers(raise_on_invalid=False)
513+
ids = s.get_identifiers()
497514
eq(ids, ['who', 'what'])
498515

516+
# if the pattern has an unrecognized capture group,
517+
# it should raise ValueError like substitute and safe_substitute do
518+
class BadPattern(Template):
519+
pattern = r"""
520+
(?P<badname>.*) |
521+
(?P<escaped>@{2}) |
522+
@(?P<named>[_a-z][._a-z0-9]*) |
523+
@{(?P<braced>[_a-z][._a-z0-9]*)} |
524+
(?P<invalid>@) |
525+
"""
526+
s = BadPattern('@bag.foo.who likes to eat a bag of @bag.what')
527+
self.assertRaises(ValueError, s.get_identifiers)
528+
499529

500530
if __name__ == '__main__':
501531
unittest.main()
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
Add :meth:`string.Template.get_identifiers` method.
1+
Add :meth:`string.Template.is_valid` and :meth:`string.Template.get_identifiers` methods.

0 commit comments

Comments
 (0)