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?