How does exec work with locals?
问题 I thought this would print 3, but it prints 1: def f(): a = 1 exec(\"a = 3\") print(a) 回答1: This issue is somewhat discussed in the Python3 bug list. Ultimately, to get this behavior, you need to do: def foo(): ldict = {} exec("a=3",globals(),ldict) a = ldict['a'] print(a) And if you check the Python3 documentation on exec, you'll see the following note: The default locals act as described for function locals() below: modifications to the default locals dictionary should not be attempted.