Python: Changing value in imported dict has no effect -


here's fun one. create file foo.py following contents:

options = {'x': 0}  def get_option(key):     foo import options     return options[key]  if __name__ == '__main__':     options['x'] = 1     print("options['x'] %d" % options['x'])     print("get_option('x') %d" % get_option('x')) 

running python foo.py gives following output:

options['x'] 1 get_option('x') 0 

i have expected result 1 in both cases. why 0 in second case?

you getting because from foo import options line in get_options() function loads new local options variable in memory value {'x':0}. if remove/comment line, got expected result, because options variable in get_options() global variable, not local.

options = {'x': 0}  def get_option(key):     # foo import options     return options[key]  if __name__ == '__main__':     options['x'] = 1     print("options['x'] %d" % options['x'])     print("get_option('x') %d" % get_option('x')) 

you can debug using id() function returns “identity” of object during it's lifetime.

for debugging code is:

options = {'x': 0}  def get_option(key):     foo import options     print("id %d in get_option" % id(options))     return options[key]  if __name__ == '__main__':     options['x'] = 1     print("id %d in main" % id(options))     print("options['x'] %d" % options['x'])     print("get_option('x') %d" % get_option('x')) 

output:

id 140051744576688 in main options['x'] 1 id 140051744604240 in get_option get_option('x') 0 

note: values of id's can changed on system.

now, can see id's different in both place, means there 2 options inside get_options() function 1 __main__.options , other 1 foo.options. but, if comment/remove line from foo import options in get_options(), same id's @ both places.


Comments