3

I have dozens of variables in a dictionary in a pickle. If certain conditions are true, I need to restore all of these variables (all different types), with the same names as the dict's keys.

I simplified the code to point out the problem. For instance, one of the keys is 'ref10_data'. If the variable is defined elsewhere in the function, it doesn't get overwritten, but I would like it to be.

import _pickle as pickle
from numpy import max

def main():
  processing_path = '/data/common/PROBSEV_DATA/processing/'
  ref10_data = 0
  restore_dict = pickle.load(open(processing_path + 'cc_rt_prob_svr.out','rb'))

  for key in restore_dict:
    globals()[key] = restore_dict[key]

  print(max(ref10_data))

if __name__ == '__main__':
  main()

'0' is what is printed. This question/answer kind of works, but it won't overwrite a variable if it is previously defined. How do I get it to re-define a variable, or is there a better way to structure this functionality? Thanks.

Community
  • 1
  • 1
weather guy
  • 397
  • 1
  • 3
  • 17

1 Answers1

0

Instead of tampering with globals, which is inellegant and unpythonic, you can simply pass the variables as keyword arguments ("kwargs") to another function:

def foo(ref10_data, another_var, yet_another_var):
    print(max(ref10_data))

def main():
    ...
    restore_dict = pickle.load(...)
    foo(**restore_dict)

This is simple, intuitive, and pythonic.

shx2
  • 61,779
  • 13
  • 130
  • 153