File tree Expand file tree Collapse file tree 3 files changed +32
-0
lines changed
Expand file tree Collapse file tree 3 files changed +32
-0
lines changed Original file line number Diff line number Diff 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.
146156Template .__init_subclass__ ()
Original file line number Diff line number Diff 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
479500if __name__ == '__main__' :
480501 unittest .main ()
Original file line number Diff line number Diff line change 1+ Add get_identifiers() method to string.Template.
You can’t perform that action at this time.
0 commit comments