gd = GlobalDict()
src = 'def foo(): print x'
compiled = compile(src, '<foo>', 'exec')
exec(compiled, {}, gd)
f = gd['foo']
f
f()
gd['x'] = 1
f()
del gd['x']
f()
Python: how to dynamically set function closure environment