0

I am using a .json config file for my project. I am using a json rather than a .py file because I really want to be able to save and load my configs, to handle different executions/models. When I load it, I get a dictionary (say config_dict). I can see three ways to use it:

1) Unfold the values within the dictionary with some code like this:

with open(path_to_config, "r") as f:
    config_dict = json.load(f)

for (k, v) in config_dict.items():
    locals()[k] = v

Now completely unfolding my config requires a bit more work, and there are several places in my code where I'd like to do so. So I figured creating a function. But listing all the variables in return() is fastidious and not very flexible. So I was thinking assigning global variables within the function, i.e. do something like this:

def f():
  global x
  x = 5

i.e., applied to my case:

def load_config(path_to_config):

    with open(path_to_config, "r") as f:
        config_dict = json.load(f)

    for (k, v) in config_dict.items():
        global globals()[k]
        globals()[k] = v

but:

a. This code doesn't work

b. I don't know if there are any risk doing so?

2) I could just use config_dict['key'] for all keys in all the code following a config load.

3) I could use *kwargs in the arguments of the functions I use, and pass my config_dict as argument. But I feel that it's not a best practice.

What's the best practice here and why?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Vincent
  • 482
  • 6
  • 22
  • This is subjective. I feel it's best to leave config handling to one class. Expose the config properties as attributes of the class using `@property`. Have an instance of this class available to whatever needs it. – rdas Sep 26 '19 at 20:36
  • If you want your stored variables to populate the global namespace, then use myconfigfile.py instead of json and simply load it with: `from myconfigfile import *` – Demi-Lune Sep 26 '19 at 21:07
  • @Demi-Lune thanks but I really want to be able to save and load my configs, to handle different executions/models – Vincent Sep 26 '19 at 21:09
  • There's no problem in /saving the file (use importlib instead of import if you want to be able to change the file name). See for instance https://stackoverflow.com/questions/5055042/whats-the-best-practice-using-a-settings-file-in-python (there's a better post that I can't find right now) – Demi-Lune Sep 26 '19 at 21:17
  • Here it is : look at the section "Programs are data" in this page https://v4.software-carpentry.org/essays/persist.html ; with repr and eval (or import) they show how to use py as a config file format. – Demi-Lune Sep 26 '19 at 21:34

0 Answers0