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

北慕城南 提交于 2019-12-18 17:37:36

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!