Call a function with argument list in python

SurDin picture SurDin · May 3, 2009 · Viewed 318.4k times · Source

I'm trying to call a function inside another function in python, but can't find the right syntax. What I want to do is something like this:

def wrapper(func, args):
    func(args)

def func1(x):
    print(x)

def func2(x, y, z):
    return x+y+z

wrapper(func1, [x])
wrapper(func2, [x, y, z])

In this case first call will work, and second won't. What I want to modify is the wrapper function and not the called functions.

Answer

itsadok picture itsadok · May 3, 2009

To expand a little on the other answers:

In the line:

def wrapper(func, *args):

The * next to args means "take the rest of the parameters given and put them in a list called args".

In the line:

    func(*args)

The * next to args here means "take this list called args and 'unwrap' it into the rest of the parameters.

So you can do the following:

def wrapper1(func, *args): # with star
    func(*args)

def wrapper2(func, args): # without star
    func(*args)

def func2(x, y, z):
    print x+y+z

wrapper1(func2, 1, 2, 3)
wrapper2(func2, [1, 2, 3])

In wrapper2, the list is passed explicitly, but in both wrappers args contains the list [1,2,3].