An idiom for code generation with exec

bruno.desthuilliers at gmail.com bruno.desthuilliers at gmail.com
Fri Jun 20 23:06:04 CEST 2008


On 20 juin, 21:41, eliben <eli... at gmail.com> wrote:
> > [1] except using compile to build a code object with the function's
> > body, then instanciate a function object using this code, but I'm not
> > sure whether it will buy you much more performance-wise. I'd personnaly
> > prefer this because I find it more explicit and readable, but YMMV.
>
> How is compiling more readable than exec -

Using compile and function(), you explicitely instanciate a new
function object, while using exec you're relying on a side effect.

> doesn't it require an extra
> step ?

Well... Your way:

   d = {}
  exec code in globals(), d
  return d['foo']

My way:

  return function(compile(code, '<string>', 'exec'), globals())

As far as I'm concern, it's two steps less - but YMMV, of course !-)

>  You generate code dynamically anyway.

Yes, indeed. Which may or not be the right thing to do here, but this
is a different question (and one I can't actually answer).




More information about the Python-list mailing list