An idiom for code generation with exec

eliben eliben at
Mon Jun 23 06:44:55 CEST 2008

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

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 =
        return None

    d = {}
    exec code.strip() in globals(), d
    return d[func_name]

Although the 'def' matching in the beginning looks a bit shoddy at
first, it should work in all cases.


More information about the Python-list mailing list