Call a Function with Argument List in Python

Call a function with argument list in python

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

Can you store functions with parameters in a list and call them later in Python?

It sounds like you want to store the functions pre-bound with parameters. You can use functools.partial to give you a function with some or all of the parameters already defined:

from functools import partial

def f(text):
print(text)

mylist = [partial(f, 'yes'), partial(f,'no')]

mylist[0]()
# yes

mylist[1]()
# no

Passing a list of parameters into a Python function

some_list = ["some", "values", "in", "a", "list", ]
func(*some_list)

This is equivalent to:

func("some", "values", "in", "a", "list")

The fixed x param might warrant a thought:

func(5, *some_list)

... is equivalent to:

func(5, "some", "values", "in", "a", "list")

If you don't specify value for x (5 in the example above), then first value of some_list will get passed to func as x param.

Append a function and its arguments to a list without calling the function immediately

Try this:

list.append( functools.partial(func1, a, b, c, d) )

Call functions on elements of list

You can use * to unpack the values in your list as parameters of your function:

def f(a, b, c):
print(a,b,c)

x = [4, 6, 10]

f(*x)

Output:

4 6 10

Just be careful that your list has the proper number of parameters.

Can I call function in python with named arguments as a variable?

You can pass a dictionary of keywords arguments to a function using the ** operator. The keys of the dictionary are the parameter names in the function.

In this case, that could be:

get_user_by(**{username_type: username})

If the variable username_type has the value 'email' then the username would be received in get_user_by as the keyword argument email.



Related Topics



Leave a reply



Submit