Python - list of function/argument tuples

Viewed 3101
def f1(n): #accepts one argument
    pass

def f2(): #accepts no arguments
    pass

FUNCTION_LIST = [(f1,(2)), #each list entry is a tuple containing a function object and a tuple of arguments
                 (f1,(6)),
                 (f2,())]

for f, arg in FUNCTION_LIST:
    f(arg)

The third time round in the loop, it attempts to pass an empty tuple of arguments to a function that accepts no arguments. It gives the error TypeError: f2() takes no arguments (1 given). The first two function calls work correctly - the content of the tuple gets passed, not the tuple itself.

Getting rid of the empty tuple of arguments in the offending list entry doesn't solve the problem:

FUNCTION_LIST[2] = (f2,)
for f,arg in FUNCTION_LIST:
    f(arg)

results in ValueError: need more than 1 value to unpack.

I've also tried iterating over the index rather then the list elements.

for n in range(len(FUNCTION_LIST)):
    FUNCTION_LIST[n][0](FUNCTION_LIST[n][1])

This gives the same TypeError in the first case, and IndexError: tuple index out of range when the third entry of the list is (f2,).

Finally, asterisk notation doesn't work either. This time it errors on the call to f1:

for f,args in FUNCTION_LIST:
    f(*args)

gives TypeError: f1() argument after * must be a sequence, not int.

I've run out of things to try. I still think the first one ought to work. Can anyone point me in the right direction?

4 Answers
Related