Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional parameters in functions and their mutable default values [duplicate]

Possible Duplicate:
“Least Astonishment” in Python: The Mutable Default Argument

I'm kind of confused about how optional parameters work in Python functions/methods.

I have the following code block:

>>> def F(a, b=[]): ...     b.append(a) ...     return b ... >>> F(0) [0] >>> F(1) [0, 1] >>> 

Why F(1) returns [0, 1] and not [1]?

I mean, what is happening inside?

like image 821
Oscar Mederos Avatar asked Jun 22 '11 06:06

Oscar Mederos


People also ask

What are default and optional parameters?

By default, all parameters of a method are required. A method that contains optional parameters does not force to pass arguments at calling time. It means we call method without passing the arguments. The optional parameter contains a default value in function definition.

What is an optional parameter in a function?

What are Optional Parameters? By definition, an Optional Parameter is a handy feature that enables programmers to pass less number of parameters to a function and assign a default value.

What is a mutable default argument?

In Python, when passing a mutable value as a default argument in a function, the default argument is mutated anytime that value is mutated. Here, "mutable value" refers to anything such as a list, a dictionnary or even a class instance.

Can parameters have default values?

In JavaScript, a parameter has a default value of undefined. It means that if you don't pass the arguments into the function, its parameters will have the default values of undefined .


1 Answers

Good doc from PyCon a couple years back - Default parameter values explained. But basically, since lists are mutable objects, and keyword arguments are evaluated at function definition time, every time you call the function, you get the same default value.

The right way to do this would be:

def F(a, b=None):     if b is None:         b = []     b.append(a)     return b 
like image 95
Ben Hayden Avatar answered Sep 22 '22 05:09

Ben Hayden