简体   繁体   中英

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

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)

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM