def build(s, loc):
exec(s, loc)
return loc
def main():
L = build('x = 1', locals())
locals().update(L)
exec('print(x)')
if __name__ == '__main__':
main()
When I run the code above, the python console will show '1'.
def build(s, loc):
exec(s, loc)
return loc
def main():
L = build('x = 1', locals())
locals().update(L)
print(x)
if __name__ == '__main__':
main()
When I run the code above, it will show 'name 'x' is not defined'.
What is the difference between them?
I modified my code for reducing ambiguity, a similar problem persists.
def main():
exec('x = 1')
exec('print(x)')
if __name__ == '__main__':
main()
This will show '1'.
def main():
exec('x = 1')
print(x)
if __name__ == '__main__':
main()
This will go wrong.