On Fri, Oct 10, 2008 at 6:50 PM, Joe Strout <joe@strout.net> wrote:

Proposed is the addition of one new attribute, and one new function, on the existing Template class, as follows:

1. 'greedy' is a new attribute that determines whether the field matches should be done in a greedy manner, equivalent to regex pattern '(.*)'; or in a non-greedy manner, equivalent to '(.*?)'.  This attribute defaults to false.

2. 'match' is a new function which accepts one parameter, an input string.  If the input string can be matched to the template pattern (respecting the 'greedy' flag), then match returns a dictionary, where each field in the pattern maps to the corresponding part of the input string.  If the input string cannot be matched to the template pattern, then match returns NOne.


   >>> from string import Template
   >>> s = Template('$name was born in ${country}')
   >>> print s.match('Guido was born in the Netherlands')
   {'name':'Guido', 'country':'the Netherlands'}

One objection is that the hardcoded pattern '(.*)' or '(.*?)' doesn't seem generally applicable; e.g. the example above would break if the sentence continued "..in the Netherlands at 19XX". It might be possible to generalize it (e.g. by passing keyword arguments with the expected regexp for each template variable, such as "name=r'.*'', country=r'\w+'") but in this case you might as well use an explicit regexp.

Regardless, you'll need more examples and more compelling use cases before this has any chance to move forward. You may start from the stdlib and see how much things could be simplified if Template.match was available.