Home > Software engineering >  Using an if statement in function argument when calling
Using an if statement in function argument when calling

Time:06-25

How to use an if statement or similar in function arguments to reduce blocks of code?

    if versionid is None:
        s3_response = s3_client.head_object(
              Bucket=bucket
            , Key=key
            )
    else:
        s3_response = s3_client.head_object(
              Bucket=bucket
            , Key=key
            , VersionId=versionid
            )

to something like this:

        s3_response = s3_client.head_object(
              Bucket=bucket
            , Key=key
            , if versionid is not None: VersionId=versionid
            )

Not able to get this working and can't find any examples so assume not possible.

CodePudding user response:

You can't use a statement where an expression is expected. Unless you know what the default value (if any) for the VersionId parameter is, you can do something like this:

args = {'Bucket': bucket, 'Key': key}
if versionid is not None:
    args['VersionId'] = versionid

s3_response = s3_client.head_object(**args)

If you do know the appropriate default, you can use the conditional expression:

# FOO is whatever the appropriate default is
s3_response = s3_client.head_object(Bucket=bucket, Key=key, Versionid=FOO if versonid is None else versionid)

(Assuming a non-None versionid will be a truthy value, you can shorten this to versionid or FOO, but be aware that 0 or FOO is 0, not FOO.)


You could write something like

s3_response = s3_client.head_object(
                Bucket=bucket,
                Key=key,
                **({} if versionid is None else {'VersionID': versionid})
              )

but I wouldn't recommend it.

  • Related