(Just a quick note for others googlin')
Ok, so modifying locals()
is not the way to go ( while modifying globals()
is supposed to work). In the meantime, exec
could be, but it's painfully slow, so, as with regular expressions, we may want to compile()
it first:
# var0 = 0; var1 = 1; var2 = 2
code_text = '\n'.join( "var%d = %d" % (n, n) for n in xrange(3) )
filename = ''
code_chunk = compile( code_text, filename, 'exec' )
# now later we can use exec:
exec code_chunk # executes in the current context