Using variable as keyword passed to **kwargs in Python

大憨熊 提交于 2019-12-09 18:43:55

问题


I have a function that updates a record via an API. The API accepts a variety of optional keyword parameters:

def update_by_email(self, email=None, **kwargs):
    result = post(path='/do/update/email/{email}'.format(email=email), params=kwargs)

I have another function that uses the first function to update an individual field in the record:

def update_field(email=None, field=None, field_value=None):
    """Encoded parameter should be formatted as <field>=<field_value>"""
    request = update_by_email(email=email, field=field_value)

This doesn't work. When I call:

update_field(email='joe@me.com', field='name', field_value='joe')

the url is encoded as:

https://www.example.com/api/do/update/email/joe@me.com?field=Joe

How can I get it to encode as:

https://www.example.com/api/do/update/email/joe@me.com?name=Joe

Thank you in advance.


回答1:


Rather than passing the parameter named as field, you can use dictionary unpacking to use the value of field as the name of the parameter:

request = update_by_email(email, **{field: field_value})

Using a mock of update_by_email:

def update_by_email(email=None, **kwargs):
    print(kwargs)

When I call

update_field("joe@me.com", "name", "joe")

I see that kwargs inside update_by_email is

{'name': 'joe'}


来源:https://stackoverflow.com/questions/22384398/using-variable-as-keyword-passed-to-kwargs-in-python

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