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?
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 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.
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.
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 .
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With