简体   繁体   中英

Using an if statement in function argument when calling

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.

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.

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