0

I have this bit of code:

from ast import literal_eval

# evil exec loop                                                                               
param_dict = literal_eval(sys.argv[1])                                                         

for key in param_dict.keys():                                                                  
    if type(param_dict[key]) != str:                                                           
        exec(key+"={}".format(param_dict[key]))                                                
    else:                                                                                      
        exec(key+"='{}".format(param_dict[key])+"'")

please don't judge me on my use of exec. A) this code is only for myself, and I trust my input and B) I find constantly referring to the dictionary as opposed to normal variables tedious. That being said, if you know of a better way to do this, I am open to it.

Now to my question. I would like to take this code and put it into a function in a different file, and then only call this function with the dictionary (or the string representing it) as an argument. But when I tried that, the program cannot find the variable names. I am guessing that these variables stay within the scope of the function, which is why they cannot be seen outside of it. Is there a way around this (without using global)?

4
  • You want to access variables created inside a function, but you don't want to use globals? Commented Apr 16, 2020 at 11:29
  • If possible. I want to use the variables in the scope just above the function, but not beyond. Commented Apr 16, 2020 at 11:39
  • How many variables are we talking about? I would probably just write them out manually. Commented Apr 16, 2020 at 12:13
  • This code is for running different simulations on a cluster. Which means a) there may be quite a few (last time I did something like this, there were over 50) and b) they can be different for different types of programs, and I don't want to manually write them out every time. The dictionary maps parameters to their values, and I want to be able to use the parameter names in the simulations in a straightforaward manner. Commented Apr 16, 2020 at 12:27

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.