by sabauma · 9y ago · 0 comments
def main():
a = 1
d = locals()
print d
d['b'] = 123
print b
print d
print d is locals()
main()
Which prints {'a': 1}
Traceback (most recent call last):
File "test.py", line 23, in <module>
main()
File "test.py", line 19, in main
print b
NameError: global name 'b' is not definedTo show that not even changes to existing local variables work, try
def main():
a = 1
d = locals()
print d
b = None
d['b'] = 123
print b
print d
print locals()
print d is locals()
which prints {'a': 1}
None
{'a': 1, 'b': 123}
{'a': 1, 'b': None, 'd': {...}}
True
I.e. changes to the dictionary returned by locals() are ignored, and calling locals() again overrides the previous values.