passing a variable argument list to a function

S

Scott

I'm trying to write a function that accepts a variable number of
arguments and passes those arguments to another function. Here is an
example:

def foo(*args):
print "I'm going to call bar with the arguments", args
bar(args)

This doesn't do quite what I want. For example, if I call foo(1,2,3,4)
then it calls bar((1,2,3,4)). It passes a tuple rather than expanding
the argument list back out.

I suspect there's a simple bit of syntax that I'm missing -- can
anyone give me a hand?

Thanks
Scott
 
C

Christian Heimes

Scott said:
I suspect there's a simple bit of syntax that I'm missing -- can
anyone give me a hand?

Yeah. It's so easy and obvious that you are going to bang your head
against the wall. :) The single star does not only collect all arguments
in a function definition. It also expands a sequence as arguments.

def egg(*args):
spam(*args)

somefunc(*(a, b, c)) is equivalent to somefunc(a, b, c).

Double star (**) does the same with keyword arguments

Christian
 
S

Scott

Yeah. It's so easy and obvious that you are going to bang your head
against the wall. :) The single star does not only collect all arguments
in a function definition. It also expands a sequence as arguments.

Thanks Christian, that worked perfectly!

Scott
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,743
Messages
2,569,478
Members
44,898
Latest member
BlairH7607

Latest Threads

Top