views:

1186

answers:

3

In a similar way to using varargs in C or C++:

fn(a, b)
fn(a, b, c, d, ...)
A: 

Pass an array..

nosatalian
Not having used Python much, this was my initial idea. Why has this answer been marked down?
CiscoIPPhone
I didn't mark it down, but I would guess it is because it is simply not the answer, and the actual answer is no more complicated than passing an array
David Sykes
An array isn't even a basic Python type. (Though you can import such a thing from the standard library.) If the answer had been 'pass a list' however that would have been less wrong, but still more work than the canonical way given in the accepted answer above.
Kylotan
+17  A: 

Yes.

def manyArgs(*arg):
  print "I was called with", len(arg), "arguments:", arg

>>> manyArgs(1)
I was called with 1 arguments: (1,)
>>> manyArgs(1, 2,3)
I was called with 3 arguments: (1, 2, 3)

As you can see, Python will give you a single tuple with all the arguments.

unwind
http://docs.python.org/tutorial/controlflow.html#more-on-defining-functions
Miles
+16  A: 

Adding to unwinds post:

You can send multiple key-value args too.

def myfunc(**kwargs):
    # kwargs is a dictionary.
    for k,v in kwargs.iteritems():
         print "%s = %s" % (k, v)

myfunc(abc=123, def=456)
# abc = 123
# def = 456

And you can mix the two:

def myfunc2(*args, **kwargs):
   for a in args:
       print a
   for k,v in kwargs.iteritems():
       print "%s = %s" % (k, v)

myfunc2(1, 2, 3, banan=123)
# 1
# 2
# 3
# banan = 123

They must be both declared and called in that order, that is the function signature needs to be *args, **kwargs, and called in that order.

Skurmedel
@Skurmedel - Here you go.
Aiden Bell
@Aiden Bell: lol thanks.
Skurmedel