tags:

views:

143

answers:

2

I have a class in python that allows me to save a function (in a database) for later use. Now I need to have a method in the class that allows me to call this function on some arguments. Since I don't know how many arguments the function has ahead of time, I have to pass them in as list. This is where things fall apart because I can't find any way to get the argument to take its arguments from the tuple. In LISP this is very easy, since there's a keyword (well just one character) '@' for exactly this purpose:

(defmacro (call function arguments)
 `(,function ,@args))

Does python do this and I've just missed it somehow? And if it doesn't, does anyone have a creative solution?

+12  A: 

Python uses * for argument expansion. If you want keyword arguments, expand a dict using **. So the macro you showed would be:

def call(function, args):
    return function(*args)

But usually the Pythonic way is to just do the call inline. There actually is a function called apply() that does exactly this, but it is deprecated because the inline way is usually cleaner.

Ants Aasma
Thank you very much.
Joe Doliner
@Joe Doliner: Thanks are nice. The way this web site works, however, you have to click the "accept" check-mark under the answer you liked the best. It's your question. If this was helpful, mark it as accepted. If you want more information, ask away.
S.Lott
+4  A: 

No, this is not missing from python. SaltyCrane explains the use of *args and **kwargs much better than I could.

James Polley