Using Python to generate code?
Alex Martelli
aleaxit at yahoo.com
Wed Sep 8 12:34:11 EDT 2004
Alexis Roda <alexis.roda at urv.es> wrote:
...
> > Yep, though output.replace(...) would be neater. But the best
> > replacement is already in the Python 2.4 standard library: it uses
> > exactly the $identifier convention, and takes a dictionary of mapping of
> > identifier to string...:
...
> > In [6]: tpl % dict(VAR='fee', START='fie', END='fofum')
> > Out[6]: u'for (fee = 1, fee < fie, fee < fofum)'
>
> If you are not contrained to using $ identifiers:
>
> d={'var':'foo', 'start':1, 'end': 100}
> 'for (%(var)s = %(start)i; %(var)s < %(end)i; %(var)s++)' % d
yeah, but the template string for this long-standing Python feature is
hard to read and hard to write, which is why 2.4 finally grew a simpler
approach -- the string.Template class.
Alex
More information about the Python-list
mailing list