Using Python to generate code?

Steven Bethard steven.bethard at gmail.com
Wed Sep 8 19:37:47 CEST 2004


Alex Martelli <aleaxit <at> yahoo.com> writes:
> 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.

Just to make the comparison as fair as possible:

2.4 Template solution
tpl = string.Template('for ($VAR = 1, $VAR < $START, $VAR < $END)')
tpl % dict(VAR='fee', START='fie', END='fofum')

<2.4 format string solution
tpl = 'for (%(VAR)s = 1, %(VAR)s < %(START)s, %(VAR)s < %(END)s)'
tpl % dict(VAR='fee', START='fie', END='fofum')

So, yes, the Template solution is cleaner, but not drastically so.  It saves 
you 3 characters per variable -- '(', ')' and 's'.  Of course the more 
variables you have to write, the bigger the deal it is, so I suspect the OP 
would much prefer the Template solution.

Steve




More information about the Python-list mailing list