问题
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?
回答1:
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.
来源:https://stackoverflow.com/questions/24197720/locals-updatedictionary-doesnt-add-all-the-variables