When overriding the pattern attribute on string.Template, with your own delimiters, exmp: change the ..to{..} to ..to@@..@@, safe_substitute method fail to restore the new delimiters, in case of keyerror. Problem is that the method return a specific value ==> """ return self.delimiter + '{' + braced + '}' """ I change it to be generic, with the help of the MatchObject.group() that return the whole match. Demonstration of the problem: >>> from string import Template >>> class MyTemplate(Template): ... pattern = r""" ... \$(?: ... (?P\&) | # Escape sequence of two delimiters ... (?P[_a-z][_a-z0-9]*)
# delimiter and a Python identifier ... @@(?P[_a-z][_a-z0-9]*)@@
# delimiter and a braced identifier ... (?P) # Other ill-formed delimiter exprs ... ) ... """ ... >>> b4_str = '$@@keyError@@ change the orignal string' >>> t = MyTemplate(b4_str) >>> res = t.safe_substitute() >>> print res ${keyError} change the orignal string >>> print res == b4_str False >>>