Using Python to generate code?

Alexis Roda alexis.roda at urv.es
Wed Sep 8 12:41:28 EDT 2004


Alex Martelli wrote:
> 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

If you come from Perl its not so hard :-). Anyway, I agree, templates 
are nicer, but not everyone is running python 2.4 ...


Alex
-- 
                                    ////
                                   (@ @)
----------------------------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