使用变量作为关键字传递给Python中的** kwargs
我有一个通过API更新记录的功能.该API接受各种可选的关键字参数:
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')
URL编码为:
https://www.example.com/api/do/update/email/joe@me.com?field=Joe
如何将其编码为:
https://www.example.com/api/do/update/email/joe@me.com?name=Joe
谢谢.
除了传递名为field
的参数外,您还可以使用字典解包将 field
的值用作参数名称:
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})
使用update_by_email
的模拟:
def update_by_email(email=None, **kwargs):
print(kwargs)
当我打电话
update_field("joe@me.com", "name", "joe")
我发现update_by_email
中的kwargs
是
{'name': 'joe'}