proposal to allow to set the delimiter in str.format to something other than curly bracket

Alia Khouri alia_khouri at yahoo.com
Mon Apr 4 17:32:18 EDT 2011


Peter Otten wrote:

> You could automatically convert from a custom format like that in your
> original post...

<snip>

Here's a class wrapping your functionality:

import re

class Template(object):
    '''uses double brackets e.g [[ob.attr]] as delims to get
      around curly bracket ({}) collisions when generating code
    '''
    _pattern = re.compile(r"\[\[|]]|\{|\}")
    _lookup = {
        "[[": "{",
        "]]": "}",
        "{": "{{",
        "}": "}}",
    }
    def __init__(self, txt):
        self.txt = txt
        self.type = type

    def _substitute(self, m):
        return self._lookup[m.group()]

    def render(self, *args, **kwds):
        return self._pattern.sub(
            self._substitute, self.txt).format(*args, **kwds)

def test_Template():
    class P: pass
    p = P()
    p.name = 'peter'
    txt = 'hello there [[o.name]]'
    t = Template(txt)
    assert t.render(o=p) == 'hello there peter'




More information about the Python-list mailing list