passing a variable argument list to a function

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Scott

    passing a variable argument list to a function

    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
  • Christian Heimes

    #2
    Re: passing a variable argument list to a function

    Scott wrote:
    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

    Comment

    • Scott

      #3
      Re: passing a variable argument list to a function

      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

      Comment

      Working...