Search code examples
pythonlocals

locals().update(dictionary) doesn't add all the variables


I have been loading variables using dictionary objects, but the values get updated. What am I missing here?

assert "run_LMM" in all_variables.keys()
locals().update(all_variables)
assert "run_LMM" in locals()

The last line is were I get an assertion error. What's going on?


Solution

  • That's the expected behaviour, by the docs:

    The contents of this dictionary should not be modified; changes may not affect the values of local and free variables used by the interpreter.

    I think, one of the reasons for that is that whether a variable is global or local is defined during the function compilation, so that in:

    def func():
        locals()['val'] = 1
        print val
    

    the last statement always reads from the global variable, since the local variable is not declared. So, ability to add locals dynamically would make life harder.