Home > OS >  Get rid of checking len(list) and call functions with/without args
Get rid of checking len(list) and call functions with/without args

Time:10-17

I've got a list, smth like this ['func1', parm1] or ['func2']

In some cases, there is no second element in the list. The method supposed to call has **kwargs argument, like def func1(self, **kwargs)

My current code is

cmd = matrix[i][0]
value = None
len_matrix = len(matrix[i])
if len_matrix > 1:
    value = matrix[i][1]
method = getattr(obj, cmd)
if len_matrix > 1:
    method(x=value)
else:
    method()

CodePudding user response:

You could use pop(0) on the list to extract the first parameter (the function name). This mutates the list so it will just contain the arguments (if any).

def example(a="a", b="b"):
    return a, b


cmd = ["example", "arg_a", "arg_b"]

def caller(args):
    func_name = args.pop(0)
    func = globals()[func_name]
    return func(*args)

caller(cmd)

CodePudding user response:

I don't think it will improve readability, but you can achieve this by creating your kwargs dictionary dynamically.

getattr(obj, matrix[i][0])(**({"x": matrix[i][1]} if len(matrix[i]) > 1 else {}))

If you possibly have more arguments you could extend that more or less easily:

arg_names = "xyzabc"
getattr(obj, matrix[i][0])(**{
    arg_names[it]: val for it, val in enumerate(matrix[i][1:])
})

Obviously you could also use arg_names[it - 1]: matrix[i][it] for it in range(1, len(matrix[i]))

Hope that helped.

  • Related