Skip to content Skip to sidebar Skip to footer

Writing To Locals() Works In Contrast To Documentation Saying Its Not

I am currently tinkering with the variable scopes and how they can be modified / copied, as I would like to postprocess some results dynamically in IPython. The confusion about loc

Solution 1:

at module scope, locals() returns the global module dict which can be modified. locals in a function are different. Here, the variable is not changed. As mentioned elsewhere, this is all implementation dependent. You can't rely on locals() working as a writer.

>>>deffoo():...    x = 2...locals()['x'] = 3...print(x)...>>>>>>foo()
2

EDIT

In cpython, local variables are turned into slots on the frame object. By the time python runs the program, "x" is no longer "x", its an index into the slot.

>>> from dis import dis
>>> dis(foo)
  20 LOAD_CONST               1 (2)
              2 STORE_FAST               0 (x)

  34 LOAD_CONST               2 (3)
              6 LOAD_GLOBAL              0 (locals)
              8 CALL_FUNCTION            010 LOAD_CONST               3 ('x')
             12 STORE_SUBSCR

  414 LOAD_GLOBAL              1 (print)
             16 LOAD_FAST                0 (x)
             18 CALL_FUNCTION            120 POP_TOP
             22 LOAD_CONST               0 (None)
             24 RETURN_VALUE

STORE_FAST 0 means to store the current value (it happens to be 2) into slot 0.

Solution 2:

Where are you reading this? Both Py 2 docs and Py 3 docs have the following disclaimer:

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.

This shows exactly what this is: an implementation detail. Sure, it works in CPython, but it might not work in the various other interpreters, like IronPython and Jython. It's what would be called a hack.

Do not rely on it updating any variables. Do not even try to do it for anything serious, as it causes undefined behaviour.

In CPython 3.6.0, help(locals) has the following note:

NOTE: Whether or not updates to this dictionary will affect name lookups in
the local scope and vice-versa is *implementation dependent* and not
covered by any backwards compatibility guarantees.

CPython 2.7.13 has no such note, however.

Post a Comment for "Writing To Locals() Works In Contrast To Documentation Saying Its Not"