Call a function with argument list in python


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):

def func1(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.

5/3/2009 3:20:08 PM

Accepted Answer

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:


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

def wrapper2(func, args): # without star

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].

5/3/2009 3:17:44 PM

The simpliest way to wrap a function

    func(*args, **kwargs)

... is to manually write a wrapper that would call func() inside itself:

    def wrapper(*args, **kwargs):
        # do something before
            return func(*a, **kwargs)
            # do something after

In Python function is an object, so you can pass it's name as an argument of another function and return it. You can also write a wrapper generator for any function anyFunc():

    def wrapperGenerator(anyFunc, *args, **kwargs):
        def wrapper(*args, **kwargs):
                # do something before
                return anyFunc(*args, **kwargs)
                #do something after
        return wrapper

Please also note that in Python when you don't know or don't want to name all the arguments of a function, you can refer to a tuple of arguments, which is denoted by its name, preceded by an asterisk in the parentheses after the function name:


For example you can define a function that would take any number of arguments:

    def testFunc(*args):
        print args    # prints the tuple of arguments

Python provides for even further manipulation on function arguments. You can allow a function to take keyword arguments. Within the function body the keyword arguments are held in a dictionary. In the parentheses after the function name this dictionary is denoted by two asterisks followed by the name of the dictionary:


A similar example that prints the keyword arguments dictionary:

    def testFunc(**kwargs):
        print kwargs    # prints the dictionary of keyword arguments

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow