1

I'll keep this one short and simple. Why does the following behaviour occur?

>>> globals()['x'] = 5
>>> x
5
>>> def f():
...    locals()['y'] = 7
...    y
...
>>> f()
Traceback (most recent call last):
  File "<pyshell#32>", line 1, in <module>
    f()
  File "<pyshell#31>", line 3, in f
    y
NameError: name 'y' is not defined

Here's an example of where this might be used:

import opcode
def foo():
    locals().update(opcode.opmap)
    #do stuff
user3002473
  • 4,835
  • 8
  • 35
  • 61

1 Answers1

3

The documentation for locals() includes:

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.

Bill Lynch
  • 80,138
  • 16
  • 128
  • 173
  • Well that was fast, thanks! – user3002473 Aug 04 '14 at 21:07
  • ... and the reason you can't modify `locals()` is that the Python interpreter optimizes access to local variables at compile time; they aren't stored in a dictionary the way globals are. – kindall Aug 04 '14 at 22:17