0

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?

3
  • This is scarily meta. Are you sure you're not over-generalizing something? Commented Apr 23, 2009 at 16:53
  • @Greg: Thanks for your concern. :) This isn't for production code. I'm going to be testing something for my school work and I thought "There has to be a way to do that in python." So I asked. :) Commented Apr 23, 2009 at 17:13
  • Hey! This is totally normal! I use this for production code all the time. Usecase: protocol implementation: dictionary of {tokens:functions} then match against tokens, call function. If the token is an explicit state, you have a state machine. Python is made for this! Not scarily meta at all. Wish I could downvote your comment Greg :-) Commented Jun 11, 2011 at 9:46

2 Answers 2

12

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.

Sign up to request clarification or add additional context in comments.

Comments

7

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.