1

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?

1
  • 1
    Actually this would be written as (apply function arguments) in Lisp (any dialect of Lisp, in fact). No macros necessary in this case. Commented Dec 30, 2009 at 8:56

2 Answers 2

12

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.

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

1 Comment

@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.
4

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.