An idiom for code generation with exec
eliben
eliben at gmail.com
Mon Jun 23 00:44:55 EDT 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
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]
Although the 'def' matching in the beginning looks a bit shoddy at
first, it should work in all cases.
Eli
More information about the Python-list
mailing list