在 boto3 调用中选择性地传递 kwargs

Selectively passing kwargs in boto3 calls

有没有一种方法可以根据变量的值在 boto3 调用中选择性地传递 kw 参数?

例如,在函数调用中
client.update_server(ServerId=server_id, Protocols=protocols, SecurityPolicyName=policy)

如果协议是 empty/None,我的电话应该是 client.update_server(ServerId=server_id, SecurityPolicyName=policy)

如果政策是 empty/None 我的电话应该是 client.update_server(ServerId=server_id, Protocols=protocols)

这可以在 python (3.7x) 中完成吗?

你可以像你说的那样使用kwargs。只需创建一个辅助函数并解析最初传入的 kwargs 以过滤掉 None 值。毕竟,kwargs 只是一个字典。

def update_server(client, **kwargs):
    new_kwargs = {k: v, for k, v in kwargs.items() if v is not None}
    client.update_server(**new_kwargs)