Python - list of tuples of functions / arguments

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)

For the third time in the loop, it tries to pass an empty set of arguments to a function that takes no arguments. He gives an error TypeError: f2() takes no arguments (1 given). The first two function calls work correctly - the contents of the tuple are passed, not the tuple itself.

Getting rid of an empty tuple of arguments in an abusive list entry does not solve the problem:

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

leads to ValueError: need more than 1 value to unpack.

I also tried iterating over the index, not the list items.

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

This gives the same TypeErrorin the first case, and IndexError: tuple index out of rangewhen the third element of the list (f2,).

Finally, asterisk notation doesn't work either. This time it is an error when called f1:

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

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

, . , . - ?

+5
4

:

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

(2) (6) - . (2,) (6,) , . :

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

. Python *args.

+8

, :

(6)

, , :

(6, )

.

+2

Try skipping *()instead (). The character *tells python to unpack the iterable that follows it, so it unpacks an empty tuple and doesn't pass anything to the function, because the tuple is empty.

0
source

For the record, a good alternative I discovered is use functools.partial. The following code does what I'm trying to do:

from functools import partial

def f1(n): #accepts one argument
    pass

def f2(): #accepts no arguments
    pass

FUNCTION_LIST = [partial(f1,2), #each list entry is a callable with the argument pre-ordained
                 partial(f1,6),
                 partial(f2)] #the call to partial is not really necessary for the entry with no arguments.

for f in FUNCTION_LIST: f()
0
source

All Articles