An idiom for code generation with exec

eliben eliben at gmail.com
Wed Jun 25 19:34:03 CEST 2008


On Jun 23, 6:44 am, eliben <eli... at gmail.com> wrote:
> Thanks for all the replies in this post. Just to conclude, I want to
> post a piece of code I wrote to encapsulate function creation in this
> way:
>
> def create_function(code):
>     """ Create and return the function defined in code.
>     """
>     m = re.match('\s*def\s+([a-zA-Z_]\w*)\s*\(', code)
>     if m:
>         func_name = m.group(1)
>     else:
>         return None
>
>     d = {}
>     exec code.strip() in globals(), d
>     return d[func_name]
>

Actually this won't work, because globals() returns the scope in which
create_function is defined, not called. So if I want to place
create_function in some utils file, the code it generates won't be
able to use auxiliary functions from the file that uses
create_function.

Eli



More information about the Python-list mailing list