views:

334

answers:

1

I haven't been able to find a good example of subclassing string.Template in Python, even though I've seen multiple references to doing so in documentation.

Are there any examples of this on the web?

I want to change the $ to be a different character and maybe change the regex for identifiers.

+3  A: 

From python docs:

Advanced usage: you can derive subclasses of Template to customize the placeholder syntax, delimiter character, or the entire regular expression used to parse template strings. To do this, you can override these class attributes:

delimiter – This is the literal string describing a placeholder introducing delimiter. The default value $. Note that this should not be a regular expression, as the implementation will call re.escape() on this string as needed.

idpattern – This is the regular expression describing the pattern for non-braced placeholders (the braces will be added automatically as appropriate). The default value is the regular expression [_a-z][a-z0-9].

Example:

from string import Template

class MyTemplate(Template):
    delimiter = '#'
    idpattern = r'[a-z][_a-z0-9]*'

>>> s = MyTemplate('#who likes $what')
>>> s.substitute(who='tim', what='kung pao')
'tim likes $what'
Nadia Alramli