7

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)
Gaurav Agrawal
  • 131
  • 1
  • 6
  • 1
    See the note in the [docs](https://docs.python.org/2/library/functions.html#locals) – Mark Dickinson Jun 02 '16 at 19:58
  • 1
    @JayWong http://meta.stackexchange.com/q/66377/248731 (also because there *are* stupid questions, and they're all over SO). – jonrsharpe Jun 02 '16 at 20:09
  • 2
    @jonrsharpe you're just contributing to the clutter and noise. Also, newbs do ask stupid questions at times as you must have at some point in your life since I am sure you're just like the rest of us. – apesa Jun 02 '16 at 20:14
  • 2
    @apesa note that you can see my questions and answers in my profile; I've had plenty of dumb questions in my time, but I've *done the research and answered them myself* (generally by finding an existing answer on SO). And if you want to stop people *"contributing to the clutter and the noise"*, start closer to home... – jonrsharpe Jun 02 '16 at 20:17
  • 1
    is it really a stupid question? ... the answer could be interesting if you are figuring out why the python scoping works like that ... if there is a good reason, it is interesting ... if there is not a good reason, it is also interesting – sol Oct 14 '22 at 13:21

1 Answers1

9

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.

Julien Palard
  • 8,736
  • 2
  • 37
  • 44