Joe Doliner
Joe Doliner

Reputation: 2230

Is this essential functional programming feature missing from python?

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?

Upvotes: 1

Views: 280

Answers (2)

James Polley
James Polley

Reputation: 8181

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

Upvotes: 4

Ants Aasma
Ants Aasma

Reputation: 54882

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.

Upvotes: 12

Related Questions