1

I have Python code which attempts to replace variables using the special syntax $[VARIABLE] (note square brackets) and string.template.safe_substitute(). This is working fine, with the one exception that when an undefined variable is referenced, instead of leaving the reference alone as safe_substitute() is documented to do it replaces the square brackets with curly ones. The advanced use of RE's in templates is not documented in detail (http://docs.python.org/2/library/string.html#template-strings) so probably I'm just using them wrong. Ideas?

Here's an example run of the test case; note that everything works fine when the var is defined:

% python tmpl.py
===$[UNDEFINED]===
===${UNDEFINED}===

% UNDEFINED=Hello python tmpl.py
===$[UNDEFINED]===
===Hello===

And here's the test case itself:

import os
from string import Template


# The strategy here is to replace $[FOO] but leave traditional
# shell-type expansions $FOO and ${FOO} alone.
# The '(?!)' below is a guaranteed-not-to-match RE.
class _Replace(Template):
    pattern = r"""
        \$(?:
        (?P<escaped>(?!))               | # no escape char
        (?P<named>(?!))                 | # do not match $FOO, ${FOO}
        \[(?P<braced>[A-Z_][A-Z_\d]+)\] | # do match $[FOO]
        (?P<invalid>)
    )
    """


if '__main__' == __name__:
    text = '===$[UNDEFINED]==='
    tmpl = _Replace(text)
    result = tmpl.safe_substitute(os.environ)
    print text
    print result

1 Answer 1

0

Template assumes the brace character is actually a brace:

string.py:194:

        if braced is not None:
            try:
                return '%s' % (mapping[braced],)
            except KeyError:
                return self.delimiter + '{' + braced + '}'

If you think it's a bug, post it up at http://bugs.python.org. Otherwise, I'd recommend just using {} as your delimiting character if possible.

1
  • I do think it's a bug, either of the code or documentation variety. Thanks for tracking it down. I guess I could have UTSL-ed too. Another solution, which is the one I went with, was to bring a copy of safe_substitute into the subclass I already had and "fix" it there. Jan 29, 2013 at 1:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.