views:

311

answers:

2

I would like to write a bit of code that calls a function specified by a given argument. EG:

def caller(func):
    return func()

However what I would also like to do is specify optional arguments to the 'caller' function so that 'caller' calls 'func' with the arguments specified (if any).

def caller(func, args):
# calls func with the arguments specified in args

Is there a simple, pythonic way to do this?

+11  A: 

You can do this by using arbitrary argument lists and unpacking argument lists.

>>> def caller(func, *args, **kwargs):
...     return func(*args, **kwargs)
...
>>> def hello(a, b, c):
...     print a, b, c
...
>>> caller(hello, 1, b=5, c=7)
1 5 7

Not sure why you feel the need to do it, though.

Paolo Bergantino
+7  A: 

This already exists as the apply function, though it is considered obsolete due to the new *args and **kwargs syntax.

>>> def foo(a,b,c): print a,b,c
>>> apply(foo, (1,2,3))
1 2 3
>>> apply(foo, (1,2), {'c':3})   # also accepts keyword args

However, the * and ** syntax is generally a better solution. The above is equivalent to:

>>> foo(*(1,2), **{'c':3})
Brian