3

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?

bereal
  • 32,519
  • 6
  • 58
  • 104
Steve Zelaznik
  • 616
  • 7
  • 16

1 Answers1

10

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.

bereal
  • 32,519
  • 6
  • 58
  • 104
  • @CharlieParker I don't think so. What's your use case? – bereal Oct 17 '17 at 07:26
  • my use case is to replicate what matlab's load function is https://www.mathworks.com/help/matlab/ref/load.html , just load variables to the namespace seamlessly and cleanly. – Charlie Parker Oct 17 '17 at 17:30
  • @CharlieParker no, that's definitely not possible, you will need some object or dict to serve as a namespace. – bereal Oct 17 '17 at 17:33
  • why does one need a dict in the middle to work as a namespace? thats the part I don't understand, things are already dumped in python (in a dictionary), why not just put them in real dictionary of namespace python is using anyway. Why add this extra data structure in the middle? – Charlie Parker Oct 17 '17 at 17:34
  • First reason is, as I mentioned in the answer, the list of the local variables is defined during the function compilation to make access optimisation possible. Second, and more important, is that Python is a generic programming language, and creating local variables dynamically is a lot of potential pain for static checkers, maintainers etc. Third, as Python saying goes, "explicit is better than implicit". – bereal Oct 17 '17 at 17:39
  • last question. Intuitively, how does the "pre-compilation" of the function make things more efficient? In what sense is it more efficient and why? Thanks for the help. :) – Charlie Parker Oct 17 '17 at 17:41
  • 1
    I think, [this question](https://stackoverflow.com/q/11241523/770830) has few very good answers explaining exactly that. – bereal Oct 17 '17 at 17:50