Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Locals update not working [duplicate]

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)
like image 861
Gaurav Agrawal Avatar asked Jun 02 '16 19:06

Gaurav Agrawal


Video Answer


1 Answers

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.

like image 53
Julien Palard Avatar answered Oct 12 '22 10:10

Julien Palard