summaryrefslogtreecommitdiffstats
path: root/Lib/string.py
diff options
context:
space:
mode:
authorBen Kehoe <bkehoe@irobot.com>2022-01-11 19:15:42 (GMT)
committerGitHub <noreply@github.com>2022-01-11 19:15:42 (GMT)
commitdce642f24418c58e67fa31a686575c980c31dd37 (patch)
tree90e9eb86f921027c33819c29490de8be68990b56 /Lib/string.py
parentcf496d657a1a82eaf9ebfb47d721676fef6effa5 (diff)
downloadcpython-dce642f24418c58e67fa31a686575c980c31dd37.zip
cpython-dce642f24418c58e67fa31a686575c980c31dd37.tar.gz
cpython-dce642f24418c58e67fa31a686575c980c31dd37.tar.bz2
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
Diffstat (limited to 'Lib/string.py')
-rw-r--r--Lib/string.py29
1 files changed, 29 insertions, 0 deletions
diff --git a/Lib/string.py b/Lib/string.py
index 261789c..2eab6d4 100644
--- a/Lib/string.py
+++ b/Lib/string.py
@@ -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__()