Use string variable ** kwargs as a named argument

I am trying to find a way to scroll through the json configuration file and use the key name as the argument name for a method that uses ** kwargs. I created a json configuration file and used key names as methods. I just add "set_" to the key name to call the correct method. I convert json to a dictionary to iterate over any default values. I want to pass argument names to ** kwargs string variable. I tried to pass the dictionary, but it doesn’t seem to me.

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]) 

The callable_method method call above passes "option_name" as the actual name of kwarg. I want to pass it so that when "shell" = parameter_name, it is passed as a string name for the argument name. The following is an example. Thus, I can iterate over any keys in the config and not worry about what I am looking for in any method that 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 in a pythonic way.

+6
python command-line kwargs
source share
1 answer

If I understand correctly what you are asking for, you can simply use the ** syntax on the caller to pass a dict that converts to kwargs.

 callable_method(user=user, **{option_name: user_defaults[option_name]}) 
+19
source share

All Articles