[Python-Dev] Extracting variables from string.Template objects

Isaac Morland ijmorlan at cs.uwaterloo.ca
Fri Jan 4 14:58:16 CET 2008


I found myself wanting to obtain the variables from a string.Template 
object.  The situation is that part of input consists of a filename 
template, and I want to make sure that all the parameter values I have are 
actually represented in the filename template.  So:

def templateVariables (template):
     """Extract the variable names from a string.Template.

     Returns a tuple of all variable names found in the template, in the order
     in which they occur.  If an invalid escape sequence occurs, the same
     error will be raised as if an attempt was made to expand the template.
     """
     result = []
     for match in template.pattern.finditer (template.template):
         if match.group ('invalid') is not None:
             # Raises ValueError
             template._invalid (match)
         if match.group ('escaped') is not None:
             continue
         # The "or None" should be moot.  It is there to ensure equivalent
         # treatment for an empty 'named' and an empty 'braced'.
         result.append (match.group ('named') or match.group ('braced') or None)
     return tuple (result)

Note that almost all the work is actually done by calling in to parts of 
the template object, so I think this should work properly with subclasses 
and other less common cases.

I would like to add this as a method of string.Template, which I think 
amounts to changing "template" to "self" and putting it in the Template 
class in string.py rather than on its own.  If the general idea is 
approved I would be happy to make a patch.

Also, on a related issue, does it make sense to scan the template string 
for invalid escape sequences in Template.__init__?  For the applications I 
can imagine of string.Template, I would prefer to get an error upon 
creating the Template object rather than arbitrarily later when I try to 
.substitute with it.

Isaac Morland			CSCF Web Guru
DC 2554C, x36650		WWW Software Specialist


More information about the Python-Dev mailing list