Using Python to generate code?

Alex Martelli aleaxit at yahoo.com
Wed Sep 8 17:57:16 CEST 2004


Albert Hofkamp <hat at se-126.se.wtb.tue.nl> wrote:

> On 7 Sep 2004 23:51:38 -0700, Tran Tuan Anh <anhtt at hotmail.com> wrote:
> > Right now, the generator program is written in C++. And I feel not so
> > comfortable with C++. I feel C++ is an overkill. Because, I need to
> > generate some code, hence in the program there are a lot of something
> > like this:
> > 
> > printf(out, "for (%s = 1, %s < %s, %s < %s )", varName, varName,
> > varName1, varname, varName2);
> > 
> > It is just too messy if I have more than 20 lines like this.
> 
> Agreed, reached that same conclusion.
> Therefore, I switched to something like
> 
> output="""for ($VAR = 1, $VAR < $START, $VAR < $END)"""

Uh, OT, but, doesn't this work better with semicolons than commas...?

> 
> 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)'



Alex



More information about the Python-list mailing list