简体   繁体   中英

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

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

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