C++ code generation from xml
phil hunt
philh at comuno.freeserve.co.uk
Mon Apr 15 10:18:14 EDT 2002
On Mon, 15 Apr 2002 11:03:04 +0300, Max Ischenko <max at malva.com.uaREMOVE.IT> wrote:
>
>Hi there.
>
>I have a Python program that uses data stored in XML file to generate some
>C++ code. The problem (or, more precisely, code smell) I have is that the
>actual generation algorithm is hardwired into python and therefore is
>cryptic, difficult to understand and maintain.
>
>Small example:
> def genBody(self, c):
> name = c.cxxClassName
> new = 'new %s(%s);' % (name, c.factoryCtorArg or '')
> if c.factoryNargs == 0:
> return '\treturn %s' % new
> body = '\t%s * c = %s\n' % (name, new)
> body = body + '\tc->setCmdArgs(args);\n'
> return '%s\treturn c;' % body
How about:
template1 = """\
return new $name($ctorArg);
"""
template2 = """\
$name * c = new $name($ctorArg);
c->setCmdArgs(args);
return c;
"""
def genBody(self, c):
substitutions = {
"name": c.cxxClassName,
"ctorArg": c.factoryCtorArg or ''}
if c.factoryNargs == 0:
return subst(template1, substitutions)
else
return subst(template2, substitutions)
def subst(formatString, args):
f = ... in formatString convert all $xxx to %(xxx)s ...
return f % args
The implementation of subst() is left as an exercise.
--
<"><"><"> Philip Hunt <philh at comuno.freeserve.co.uk> <"><"><">
"I would guess that he really believes whatever is politically
advantageous for him to believe."
-- Alison Brooks, referring to Michael
Portillo, on soc.history.what-if
More information about the Python-list
mailing list