Selectively passing kwargs in boto3 calls

Question:

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)?

Asked By: Niru

||

Answers:

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)
Answered By: gold_cy

Take out the "," between v and for.

new_kwargs = {k: v, for k, v in kwargs.items() if v is not None}
                    ^
SyntaxError: invalid syntax

Like This

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)
Answered By: user3389126