开发者

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 anyo开发者_StackOverflowne have a creative solution?


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜