在Python中将变量作为传递给**kwargs的关键字使用
我有一个函数,它通过一个API来更新记录。这个API可以接受很多可选的关键词参数:
def update_by_email(self, email=None, **kwargs):
result = post(path='/do/update/email/{email}'.format(email=email), params=kwargs)
我还有另一个函数,它使用第一个函数来更新记录中的某个字段:
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)
但是这样做不行。当我调用:
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
我想要的URL应该是:
https://www.example.com/api/do/update/email/joe@me.com?name=Joe
提前谢谢你。
1 个回答
17
与其直接传递一个叫做 field
的参数,不如用字典解包的方式,把 field
的值当作参数的名字来用:
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'}