Search code examples
pythonfunctionargumentso3d

How to pass a variable as an argument to a function only if the variable exists


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 ?


Solution

  • 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