Using Python to generate code?

Jeremy Bowers jerf at jerf.org
Wed Sep 8 03:35:05 EDT 2004


On Tue, 07 Sep 2004 23:51:38 -0700, Tran Tuan Anh wrote:
> 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.

It looks like you want a templater. I don't know what such programs exist
for C++, if any, or how good they are. 

You may get a lot of milage out of just adding some utility functions, to
turn that to something like

forFromOne(out, var, max, min);

Changing languages is pretty drastic if you have working, trusted code.
(If those words don't describe your code, then that assessment may change.)

> So my question is: 
> 1. Can Python help to solve this issue?

Maybe a little, but if the above code snippet is representative, the
Python equivalent of that isn't much shorter. Python would start to shine
if you want to start doing smarter things with the data, but without
knowing about the data it is hard to be specific. Basically, the moment
you aren't just assembling strings, Python will *quite likely* have an
advantage. 

(I find it very likely that a Pythonic outlook on the problem would allow
significant simplification at acceptable effort levels, but I can't
*promise* that; if all you really, honestly need is printf, which I think
would be rare but certainly conceivable, then you may get no advantage.)

> 2. Does Python has a parser? It seems to me that there is no-standard
> Parser for Python right now. If it is the case, can I interface Python
> with existing cup and lex?

Why are you asking about a parser when you are talking about *outputting*
code? Is there something left out of the problem description?

There are a lot of parsers for Python, covering a wide range of needs.




More information about the Python-list mailing list