8000 bpo-46307: Add string.Template.get_identifiers() method · python/cpython@319c8d7 · GitHub
[go: up one dir, main page]

Skip to content

Commit 319c8d7

Browse files
committed
bpo-46307: Add string.Template.get_identifiers() method
1 parent 3d11c1b commit 319c8d7

File tree

3 files changed

+32
-0
lines changed

3 files changed

+32
-0
lines changed

Lib/string.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,16 @@ def convert(mo):
141141
self.pattern)
142142
return self.pattern.sub(convert, self.template)
143143

144+
def get_identifiers(self, *, raise_on_invalid=True):
145+
ids = []
146+
for mo in self.pattern.finditer(self.template):
147+
named = mo.group('named') or mo.group('braced')
148+
if named is not None and named not in ids:
149+
ids.append(named)
150+
elif mo.group('invalid') is not None and raise_on_invalid:
151+
self._invalid(mo)
152+
return ids
153+
144154
# Initialize Template.pattern. __init_subclass__() is automatically called
145155
# only for subclasses, not for the Template class itself.
146156
Template.__init_subclass__()

Lib/test/test_string.py

Lines changed: 21 additions & 0 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_get_identifiers(self):
479+
eq = self.assertEqual
480+
raises = self.assertRaises
481+
s = Template('$who likes to eat a bag of ${what} worth $$100')
482+
ids = s.get_identifiers()
483+
eq(ids, ['who', 'what'])
484+
485+
# repeated identifiers only included once
486+
s = Template('$who likes to eat a bag of ${what} worth $$100; ${who} likes to eat a bag of $what worth $$100')
487+
ids = s.get_identifiers()
488+
eq(ids, ['who', 'what'])
489+
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
495+
s = Template('$who likes to eat a bag of ${what} worth $100')
496+
ids = s.get_identifiers(raise_on_invalid=False)
497+
eq(ids, ['who', 'what'])
498+
478499

479500
if __name__ == '__main__':
480501
unittest.main()
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Add get_identifiers() method to string.Template.

0 commit comments

Comments
 (0)
0