Frage

I'm trying to make a function designed to call another function multiple times:

def iterator(iterations, function, *args):  
#called as:
iterator(5, my_function, arg1, arg2, arg3)  

Note that the number of arguments here is variable: could 1, could be 2, could be 10. fill them in based on the function that is being called.

def iterator(iterations, function, *args):
  for i in range(iteration):
    temp = function(args)
  return temp

The problem here is: TypeError: my_function() takes exactly 4 arguments (1 given)

And this is because (arg1, arg2, arg3, arg4) are being treated as a single argument.

How do I get around this?

War es hilfreich?

Lösung

By using the same syntax when applying the args sequence:

temp = function(*args)

The *args syntax here is closely related to the *args function parameter syntax; instead of capturing an arbitrary number of arguments, using *args in a call expands the sequence to separate arguments.

You may be interested to know that there is a **kwargs syntax too, to capture and apply keyword arguments:

def iterator(iterations, function, *args, **kwargs):
    for i in range(iteration):
        temp = function(*args, **kwargs)
    return temp

Andere Tipps

Try this, unpacking the argument list (a.k.a. splatting it):

function(*args)

From the example in the documentation, you'll see that this is what you need:

range(3, 6)    # ok
range([3, 6])  # won't work
range(*[3, 6]) # it works!
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top