Reputation: 21625
Python newb here. Suppose you have a function like
def myfunc(a = "apple", *args):
print(a)
for b in args:
print(b + "!")
How do you pass a set of unnamed arguments to *args without altering the default argument?
What I want to do is
myfunc(,"banana", "orange")
and get the output
apple
banana!
orange!
but this doesn't work.
(I'm sure this has been discussed before but all my searching came up empty)
Upvotes: 2
Views: 119
Reputation: 250891
In Python 3 you can do this by changing a
to a keyword only argument:
>>> def myfunc(*args, a="apple"):
print(a)
for b in args:
print(b + "!")
...
>>> myfunc("banana", "orange")
apple
banana!
orange!
>>> myfunc("banana", "orange", a="watermelon")
watermelon
banana!
orange!
In Python 2 you'll have to do something like this:
>>> def myfunc(*args, **kwargs):
a = kwargs.pop('a', 'apple')
print a
for b in args:
print b + "!"
Upvotes: 2