I want to make a function that is flexible with regard to unpacking the number of input variables.
More specifically, for example I have the following:
def flexi_func(vars):
func_var_a, func_var_b, func_var_c, func_var_d = vars
#do something
my_vars = [var_a, var_b, var_c, var_d]
flexi_func(my_vars)
This works fine if the number of input variables is 4. But say I want to have the same function operate on just three input variables, or two. Assume the 'do something' bit is already flexible. Then to unpack the variables I can write
def flexi_func(vars):
if len(vars) == 4:
func_var_a, func_var_b, func_var_c, func_var_d = vars
elif len(vars) == 3:
func_var_a, func_var_b, func_var_c = vars
elif len(vars) == 2:
func_var_a, func_var_b = vars
#do something
And this works fine too. It just seems a bit clunky to me, especially if I had N>4 variables. Is there a cleaner, more Pythonic way to unpack a tuple in such a way that I can use the unpacked variables?
I know from this question I can do something like this (in Python 3):
foo, bar, *other = func()
but I would need to do more work to access the stuff in other
, so it's no better than my if...elif...
approach.