Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

default values for variable argument list in Python

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.

like image 377
deamon Avatar asked May 03 '10 16:05

deamon


People also ask

What is default value of variable in Python?

Default values indicate that the function argument will take that value if no argument value is passed during the function call. The default value is assigned by using the assignment(=) operator of the form keywordname=value.

What is default argument function in Python?

Default argument is fallback value In Python, a default parameter is defined with a fallback value as a default argument. Such parameters are optional during a function call. If no argument is provided, the default value is used, and if an argument is provided, it will overwrite the default value.

Can an argument be a list in Python?

You can send any data types of argument to a function (string, number, list, dictionary etc.), and it will be treated as the same data type inside the function.


2 Answers

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.

like image 112
kwatford Avatar answered Oct 20 '22 23:10

kwatford


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]
  • Stolen from: http://www.network-theory.co.uk/docs/pytut/DefaultArgumentValues.html

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

like image 22
Paul Hildebrandt Avatar answered Oct 21 '22 00:10

Paul Hildebrandt