Use string variable **kwargs as named argument

99封情书 提交于 2019-12-23 09:25:57

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/15949816/use-string-variable-kwargs-as-named-argument

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!