[Python-Dev] Re: Alternative placeholder delimiters for PEP 292 (original) (raw)

Andrew Durdin adurdin at gmail.com
Fri Sep 3 15:55:25 CEST 2004


On Mon, 30 Aug 2004 16:11:34 +1000, Andrew Durdin <adurdin at gmail.com> wrote:

A Yet Simpler Proposal, modifying that of PEP 292

I propose that the Template module not use $ to set off placeholders; instead, placeholders are delimited by braces {}.

Barry, would you care to comment on my proposal, particularly my points in the rationale for it?

I've just taken the 2.4a3 Template class and modified it to fit this proposal. The result is below. I've also got a modified unit test and tex file to account for the changes at http://andy.durdin.net/test_pep292_braces.py and http://andy.durdin.net/bracetmpl.text -- I'd make a complete patch, but I'm not sure what tools to use (I'm running Win2k): can someone point me in the right direction?

#################################################################### import re as _re

class Template(unicode): """A string class for supporting {}-substitutions.""" slots = []

# Search for {{, }}, {identifier}, and any bare {'s or }'s
pattern = _re.compile(r"""
  (?P<escapedlt>\{{2})|              # Escape sequence of two { braces
  (?P<escapedrt>\}{2})|              # Escape sequence of two } braces
  {(?P<braced>[_a-z][_a-z0-9]*)}|    # $ and a brace delimited identifier
  (?P<bogus>\{|\})                   # Other ill-formed { or } expressions
""", _re.IGNORECASE | _re.VERBOSE)

def __mod__(self, mapping):
    def convert(mo):
        if mo.group('escapedlt') is not None:
            return '{'
        if mo.group('escapedrt') is not None:
            return '}'
        if mo.group('bogus') is not None:
            raise ValueError('Invalid placeholder at index %d' %
                             mo.start('bogus'))
        val = mapping[mo.group('braced')]
        return unicode(val)
    return self.pattern.sub(convert, self)

class SafeTemplate(Template): """A string class for supporting {}-substitutions.

This class is 'safe' in the sense that you will never get KeyErrors if
there are placeholders missing from the interpolation dictionary.  In that
case, you will get the original placeholder in the value string.
"""
__slots__ = []

def __mod__(self, mapping):
    def convert(mo):
        if mo.group('escapedlt') is not None:
            return '{'
        if mo.group('escapedrt') is not None:
            return '}'
        if mo.group('bogus') is not None:
            raise ValueError('Invalid placeholder at index %d' %
                             mo.start('bogus'))
        braced = mo.group('braced')
        try:
            return unicode(mapping[braced])
        except KeyError:
            return '{' + braced + '}'
    return self.pattern.sub(convert, self)

del _re



More information about the Python-Dev mailing list