Curcuma_
Curcuma_

Reputation: 901

Pass an optional parameter based on value in Python3

I have a parameter that can be None or a String. In case it is None, I cannot pass it as parameter, as the library does not support None values nor empty strings. The library does not accept dictionaries as input neither. On the other side, I don't really want to write such a horrible alternative!

if lifecycle_policy_name:
    response = client.create_notebook_instance(
        NotebookInstanceName=NotebookInstanceName,
        InstanceType=InstanceType,
        SubnetId=SubnetId,
        SecurityGroupIds=SecurityGroupIds,
        RoleArn=RoleArn,
        Tags=Tags,
        DirectInternetAccess='Disabled',
        VolumeSizeInGB=10,
        RootAccess='Disabled',
        KmsKeyId=kms_key.get('KeyId'),
        LifecycleConfigName=lifecycle_policy_name
    )
else:
    response = client.create_notebook_instance(
        NotebookInstanceName=NotebookInstanceName,
        InstanceType=InstanceType,
        SubnetId=SubnetId,
        SecurityGroupIds=SecurityGroupIds,
        RoleArn=RoleArn,
        Tags=Tags,
        DirectInternetAccess='Disabled',
        VolumeSizeInGB=10,
        RootAccess='Disabled',
        KmsKeyId=kms_key.get('KeyId'),
    )

So as you can guess, this is calling a Boto3 api.

Upvotes: 2

Views: 764

Answers (1)

L3viathan
L3viathan

Reputation: 27283

You could try using keyword argument expansion:

kwargs = dict(
    NotebookInstanceName=NotebookInstanceName,
    InstanceType=InstanceType,
    SubnetId=SubnetId,
    SecurityGroupIds=SecurityGroupIds,
    RoleArn=RoleArn,
    Tags=Tags,
    DirectInternetAccess='Disabled',
    VolumeSizeInGB=10,
    RootAccess='Disabled',
    KmsKeyId=kms_key.get('KeyId'),
)

if lifecycle_policy_name:
    kwargs["LifecycleConfigName"] = lifecycle_policy_name
response = client.create_notebook_instance(
    **kwargs
)

Upvotes: 3

Related Questions