Skip to content

bpo-46307: Add string.Template.get_identifiers() method #30493

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Jan 11, 2022
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions Lib/string.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,16 @@ def convert(mo):
self.pattern)
return self.pattern.sub(convert, self.template)

def get_identifiers(self, *, raise_on_invalid=True):
ids = []
for mo in self.pattern.finditer(self.template):
named = mo.group('named') or mo.group('braced')
if named is not None and named not in ids:
ids.append(named)
elif mo.group('invalid') is not None and raise_on_invalid:
self._invalid(mo)
return ids

# Initialize Template.pattern. __init_subclass__() is automatically called
# only for subclasses, not for the Template class itself.
Template.__init_subclass__()
Expand Down
21 changes: 21 additions & 0 deletions Lib/test/test_string.py
Original file line number Diff line number Diff line change
Expand Up @@ -475,6 +475,27 @@ class PieDelims(Template):
self.assertEqual(s.substitute(dict(who='tim', what='ham')),
'tim likes to eat a bag of ham worth $100')

def test_get_identifiers(self):
eq = self.assertEqual
raises = self.assertRaises
s = Template('$who likes to eat a bag of ${what} worth $$100')
ids = s.get_identifiers()
eq(ids, ['who', 'what'])

# repeated identifiers only included once
s = Template('$who likes to eat a bag of ${what} worth $$100; ${who} likes to eat a bag of $what worth $$100')
ids = s.get_identifiers()
eq(ids, ['who', 'what'])

# invalid identifiers are raised
s = Template('$who likes to eat a bag of ${what} worth $100')
raises(ValueError, s.get_identifiers)

# invalid identifiers are ignored with raise_on_invalid=False
s = Template('$who likes to eat a bag of ${what} worth $100')
ids = s.get_identifiers(raise_on_invalid=False)
eq(ids, ['who', 'what'])


if __name__ == '__main__':
unittest.main()
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Add :meth:`string.Template.get_identifiers` method.