我无法使用exec()创建局部变量。我尝试了exec(instruction)
,exec(instruction, locals())
,但是没有用。只有exec(instruction, globals())
有效,但是变量是在全局级别创建的,这不是我想要的。这是一段说明我的问题的代码
# remove all variables previously stored in the environment
for name in dir():
if not name.startswith('_'):
del globals()[name]
def f1():
instruction = 'bar=1'
# exec(instruction) # NameError: name 'bar' is not defined
# exec(instruction, locals()) # NameError: name 'bar' is not defined
exec(instruction, globals()) # okish, but not the way I want cause bar is built at the globa scope
print('bar={} from inside f1'.format(bar))
print('test for global variable')
instruction = 'foo=1'
exec(instruction)
print('foo={}'.format(foo))
print('test for local variable')
f1()
print('bar={} from the outside'.format(bar)) # should raise NameError here but it doesn't