mirror of
https://github.com/python/cpython.git
synced 2025-08-28 04:35:02 +00:00
bpo-46307: Add string.Template.get_identifiers() method (GH-30493)
Add `string.Template.get_identifiers()` method that returns the identifiers within the template. By default, raises an error if it encounters an invalid identifier (like `substitute()`). The keyword-only argument `raise_on_invalid` can be set to `False` to ignore invalid identifiers (like `safe_substitute()`). Automerge-Triggered-By: GH:warsaw
This commit is contained in:
parent
cf496d657a
commit
dce642f244
4 changed files with 100 additions and 0 deletions
|
@ -141,6 +141,35 @@ class Template:
|
|||
self.pattern)
|
||||
return self.pattern.sub(convert, self.template)
|
||||
|
||||
def is_valid(self):
|
||||
for mo in self.pattern.finditer(self.template):
|
||||
if mo.group('invalid') is not None:
|
||||
return False
|
||||
if (mo.group('named') is None
|
||||
and mo.group('braced') is None
|
||||
and mo.group('escaped') is None):
|
||||
# If all the groups are None, there must be
|
||||
# another group we're not expecting
|
||||
raise ValueError('Unrecognized named group in pattern',
|
||||
self.pattern)
|
||||
return True
|
||||
|
||||
def get_identifiers(self):
|
||||
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:
|
||||
# add a named group only the first time it appears
|
||||
ids.append(named)
|
||||
elif (named is None
|
||||
and mo.group('invalid') is None
|
||||
and mo.group('escaped') is None):
|
||||
# If all the groups are None, there must be
|
||||
# another group we're not expecting
|
||||
raise ValueError('Unrecognized named group in pattern',
|
||||
self.pattern)
|
||||
return ids
|
||||
|
||||
# Initialize Template.pattern. __init_subclass__() is automatically called
|
||||
# only for subclasses, not for the Template class itself.
|
||||
Template.__init_subclass__()
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue