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

前端 未结 1 728
名媛妹妹
名媛妹妹 2020-12-17 06:35

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()
local         


        
相关标签:
1条回答
  • 2020-12-17 07:03

    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.

    0 讨论(0)
提交回复
热议问题