Using Python to generate code?

Alexis Roda alexis.roda at urv.es
Wed Sep 8 18:30:09 CEST 2004


Alex Martelli wrote:
>>output=string.replace(output,"$VAR",varName)
>>output=string.replace(output,"$START",varName1)
>>output=string.replace(output,"$END",varName2)
>>
>>Obviously, this can be enhanced.
>>(use other conventions than $identifier, and performing the substitution
>>in a loop).
>>BTW: I am not sure string.replace works OK as shown here.
> 
> 
> 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 [4]: tpl=string.Template('for ($VAR = 1, $VAR < $START, $VAR <
> $END)') 
> 
> In [5]: tpl % dict(VAR='foo', START='bar', END='baz')
> Out[5]: u'for (foo = 1, foo < bar, foo < baz)'
> 
> 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

-> 'for (foo = 1; foo < 100; foo++)'



Regards
-- 
                                    ////
                                   (@ @)
----------------------------oOO----(_)----OOo--------------------------
<>               Ojo por ojo y el mundo acabara ciego
/\ Alexis Roda - Universitat Rovira i Virgili - Reus, Tarragona (Spain)
-----------------------------------------------------------------------




More information about the Python-list mailing list