Using Python to generate code?

Albert Hofkamp hat at se-126.se.wtb.tue.nl
Wed Sep 8 17:30:57 CEST 2004


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

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.

In a sense, I am using the string replacement to substitute variables
names thus making my own text templating system.

> 1. Can Python help to solve this issue?

yep.

> 2. Does Python has a parser? It seems to me that there is no-standard

yes, several.
I have good experiences with spark. you have to be careful what you
enter, and it is not fast, but it can handle just about any
grammar you can think of.

> P/S: Also because it is NO big code generator, it only needs to
> generate some simple codes. Hence, using some abstract-syntax-tree
> library is also too an overkill.

Anything small, simple, and beautiful grows ...... 


:-)

Albert
-- 
Unlike popular belief, the .doc format is not an open publically available format.



More information about the Python-list mailing list