An idiom for code generation with exec

Maric Michaud maric at aristote.info
Mon Jun 23 04:39:48 EDT 2008


Le Monday 23 June 2008 09:22:29 Bruno Desthuilliers, vous avez écrit :
> > With some help from the guys at IRC I came to realize your way doesn't
> > do the same. It creates a function that, when called, creates 'foo' on
> > globals(). This is not exactly what I need.
>
> I possibly messed up a couple things in the arguments, flags etc - I
> very seldom use compile() and function(). The point was that  it didn't
> require any extra step.

In the argument list  of function type, the code object in first place is 
expected to be created directly (no exec - eval) with the python type 'code' 
(either found as types.CodeType or new.code).


In [24]: types.CodeType?
Type:           type
Base Class:     <type 'type'>
String Form:    <type 'code'>
Namespace:      Interactive
Docstring:
    code(argcount, nlocals, stacksize, flags, codestring, constants, names,
          varnames, filename, name, firstlineno, lnotab[, freevars[, 
cellvars]])

    Create a code object.  Not for the faint of heart.

                                      ^^^^^^^^^^^^^^^

Even if it looks more "object oriented", I'm not sure it's actually the good 
solution for the original problem. I think these interface are not a 
replacement for the quick eval-exec idiom but more intended to make massive 
code generation programs object oriented and closer to python internals.

AFAIK, the only use case I see code generation (eval - exec, playing with code 
objects) as legitime in python is in programs that actually do code 
generation, that is, parse and compile code from textual inputs (application 
buillders).

If code generation is not the best, and I fail to see any performance issue 
that could explain such a choice, except a misunderstanding of 
what "compilation" means in python, just don't use it, use closures or 
callable instances, there are many way to achieve this.

-- 
_____________

Maric Michaud



More information about the Python-list mailing list