7

Is it possible to set a default value for a variable argument list in Python 3?

Something like:

def do_it(*args=(2, 5, 21)):
     pass

I wonder that a variable argument list is of type tuple but no tuple is accepted here.

2 Answers 2

7

If not syntactically, then depending on what behavior you want:

def do_it(*args):
    if not args: args = (2, 5, 21)

or

def do_it(a=2, b=5, c=21, *args):
    args = (a,b,c)+args

should do it.

1

Initializing a list like that usually isn't a good idea.

The default value is evaluated only once. This makes a difference when the default is a mutable object such as a list, dictionary, or instances of most classes. For example, the following function accumulates the arguments passed to it on subsequent calls

def f(a, L=[]):
    L.append(a)
    return L

print f(1)
print f(2)
rint f(3)

This will print

[1]
[1, 2]
[1, 2, 3]

I generally check it something is passed in and if not then init it in the function body.

2
  • 3
    If the objects inside the tuple are immutable, then the OP's example is safe since the tuple itself is immutable as well. May 3, 2010 at 16:30
  • 1
    You are so right. I was thinking of mutable objects which a tuple isn't. Thanks for the correction. May 3, 2010 at 18:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.