Why is it bad idea to modify locals in python?
What documentation says is that when you have a local x variable and do locals()[‘x’] = 42, then x may still point to the old object. def foo(): x = 0xABCD locals()[‘x’] = 42 print(x) foo()
What documentation says is that when you have a local x variable and do locals()[‘x’] = 42, then x may still point to the old object. def foo(): x = 0xABCD locals()[‘x’] = 42 print(x) foo()
Rather than create your own object, you can use argparse.Namespace: from argparse import Namespace ns = Namespace(**mydict) To do the inverse: mydict = vars(ns)
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 … Read more