I am trying to figure out a way to loop through a json config file and use a key name as the argument name to a method that uses **kwargs. I have created a json config file and used key names as methods. I just append "set_" to the key name to call the correct method. I convert the json to a dictionary to loop through any of the defaults. I want to pass argument names to **kwargs by a string variable. I tried to pass a dictionary but it doesn't seem to like that.
user_defaults = config['default_users'][user]
for option_name, option_value in user_defaults.iteritems():
method = "set_" + option_name
callable_method = getattr(self, method)
callable_method(user = user, option_name = user_defaults[option_name])
Calling the callable_method above passes "option_name" as the actual name of the kwarg. I want to pass it so that when "shell" = option_name that it gets passed as the string name for the argument name. An example is below. That way I can loop through any keys in the config and not worry about what I'm looking for in any method I write to accomplish something.
def set_shell(self, **kwargs):
user = kwargs['user']
shell = kwargs['shell']
## Do things now with stuff
Any help is appreciated I am new to python and still learning how to do things the pythonic way.
If I understand correctly what you're asking, you can just use the **
syntax on the calling side to pass a dict that is converted into kwargs.
callable_method(user=user, **{option_name: user_defaults[option_name]})