Why below is not working inside function but working outside?
def foo():
common = {'abc' : 'xyz'}
print(locals())
locals().update(common)
print(locals(),abc)
foo()
Error : NameError: global name 'abc' is not defined
If i run it outside function, it works
common = {'abc' : 'xyz'}
print(locals())
locals().update(common)
print(locals(),abc)
According to the locals documentation:
Note The contents of this dictionary should not be modified; changes may not affect the values of local and free variables used by the interpreter.
So it's not working because it's not intended to work. But to answer your question now, it works in the global scope because modifying the globals
is possible, the globals documentation don't have the note telling "this [...] should not be modified".
And, obviously, when you're in the global scope, global is locals:
>>> globals() is locals()
True
So you're modifying globals, which is permitted.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With