Home > Software design >  How to pass a variable as an argument to a function if the variable exists
How to pass a variable as an argument to a function if the variable exists

Time:12-09

I want to use a function and pass an argument to it whether a variable exists. If the variable does not exist, then I want to use the function with the default value of the argument.

So far my code looks like this:

if transformation:
    '''
    If there is a computed transformation
    take it as an initial value.
    '''
    transformation = o3d.pipelines.registration.registration_icp(source,
                                                                    target,
                                                                    max_cor_dist,
                                                                    transformation).transformation
else:
    '''
    If there is not a computed transformation
    do not take an initial value.
    '''
    transformation = o3d.pipelines.registration.registration_icp(source,
                                                                    target,
                                                                    max_cor_dist).transformation

I feel like there is a better way to write this, any suggestions ?

CodePudding user response:

args = [source, target, max_cor_dist]
if transformation:
    args.append(transformation) 
transformation = o3d...registration_icp(*args).transformation

CodePudding user response:

You can construct just the different arguments to be passed and then use argument unpacking, like this

args = (source, target, max_cor_dist, transformation) if transformation \
    else (source, target, max_cor_dist)
o3d.pipelines.registration.registration_icp(*args).transformation
  • Related