Skip to content
Advertisement

In python is it possible to extract variables from a list inside a function call

I’m attempting to create a common create function that executes a function call to an SDK

func: The SDK function is passed as my first parameter and the function itself can’t be edited
request: This is a object that every create end point expects
args: parameter list that will vary depending on the SDK function passed

SDK function signatures
def create_a(self, create_type_a_details):
def create_b(self, extra_val_one create_type_b_details):
def create_c(self, extra_val_one, extra_val_two, create_type_c_details):


Current implementation

def create_resource(func, request, *args):

        try:
          if len(args) == 1:
            response = func(args[0], request)
          elif len(args) == 2:
            response = func(args[0], args[1], request)
          else:
            response = func(request)
        return response.data

    except ServiceError as e:
        log.error("Failed create operation {message}".format(message=e.message))
        raise e


I don’t like the above solution for obvious reasons. If there is another SDK create function that takes a third parameter before the request object, I will need to add a new elif.

Is there a way I could call the SDK function with a dynamic set of parameters without editing the SDK functions to extract the values? Can I use a Lamba inside of the function call?

thanks Donagh

Advertisement

Answer

You may just expand args to give each element as a different parameter :

def create_resource(func, request, *args):
    response = func(*args, request)
    return response.data
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement