An idiom for code generation with exec
george.sakkis at gmail.com
Sat Jun 21 17:02:34 CEST 2008
On Jun 21, 9:40 am, eliben <eli... at gmail.com> wrote:
> > > I see. In my case I only evaluate function definitions with 'exec', so
> > > I only need to de-indent the first line, and the others can be
> > > indented because they're in a new scope anyway. What you suggest works
> > > for arbitrary code and not only function definitions. It's a nice
> > > trick with the "if 1:" :-)
> > Have you actually profiled your code? Or are you just basing this
> > assumptions on guesses?
> First of all, I see absolutely no connection between your question and
> the text you quote. Is there? Or did you pick one post randomly to
> post your question on?
> Second, yes - I have profiled my code.
> Third, this is a very typical torture path one has to go through when
> asking about code generation. It is true of almost all communities,
> except Lisp, perhaps. You have to convince everyone that you have a
> real reason to do what you do. The simple norm of getting a reply to
> your question doesn't work when you get to code generation. I wonder
> why is it so. How many people have been actually "burned" by bad code
> generation techniques, and how many are just parroting "goto is evil"
> because it's the accepted thing to say. This is an interesting point
> to ponder.
It's not as much that many people have been burned but that, like
goto, 99% of the time there are better alternatives. Off the top of my
head, two recurring threads in c.l.py related to dynamic code
generation and evaluation are:
- Asking how to dynamically generate variable names ("for i in
xrange(10): exec 'x%d = %d' % (i,i)") instead of using a regular
- Using function names instead of the actual function objects and
calling eval(), not knowing that functions are first-class objects (or
not even familiar with what that means).
So even if your use case belongs to the exceptional 1% where dynamic
code generation is justified, you should expect people to question it
More information about the Python-list