Search code examples
pythonpython-3.xboto3keyword-argument

Selectively passing kwargs in boto3 calls


Is there a way to selectively pass kw arguments on a boto3 call based on the value of the variable?

For example, in a function call
client.update_server(ServerId=server_id, Protocols=protocols, SecurityPolicyName=policy)

if protocols is empty/None, my call should be client.update_server(ServerId=server_id, SecurityPolicyName=policy)

And if policy is empty/None my call should be client.update_server(ServerId=server_id, Protocols=protocols)

Is this possible to do in python (3.7x)?


Solution

  • You can use kwargs as you mention. Just create a helper function and parse the originally passed in kwargs to filter out the None values. After all, kwargs is just a dictionary.

    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)