2

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.

1 Answer 1

3

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
)
Sign up to request clarification or add additional context in comments.

6 Comments

I saw this and thought this would be read as a regular dictionary, so it is not the case right ? if yes, then this is fantastic !
kwargs is a regular dictionary, I was just to lazy to use a normal dictionary literal, since I could just copy-paste most of your code with the dict() "constructor" :D
Ah, and in case you mean how it's used: That's just **-unpacking, see e.g. this PEP.
probably the two stars means deconstruction or something. because I will try and if it is a regular dictionary it won't work :o
@Curcuma_ Exactly, you can use single asterisks to unpack iterables like lists into positional arguments, and double asterisks to unpack mappings like dictionaries into keyword arguments.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.