Curious function argument

Denis McMahon denismfmcmahon at gmail.com
Wed Nov 12 09:03:58 EST 2014


On Wed, 12 Nov 2014 14:07:14 +0100, ast wrote:

[function def with mutable default parameter]

> I understand that the author wants to implement a global variable x . It
> would be better to write 'global x' inside the function.

It may not be the case that the purpose was to implement a global 
variable, but rather to illustrate what happens when you use a mutable 
default parameter.

> At first test() function call, it prints 0, that's OK.
> But at the second call, since we dont pass any argument to test(), x
> should be equal to its default value [0] (a single item list). But it
> seems that Python keeps the original object whose content has been
> changed to 1.

This is explained in the docs:

https://docs.python.org/3/reference/compound_stmts.html#function-
definitions

Default parameter values are evaluated from left to right *when the 
function definition is executed*[1]. This means that the expression is 
evaluated once, when the function is defined, and that the same “pre-
computed” value is used for each call. This is especially important to 
understand when a default parameter is a mutable object, such as a list 
or a dictionary: if the function modifies the object (e.g. by appending 
an item to a list), the default value is in effect modified.

[1] ie when the function is 'compiled', not each time it executes.

-- 
Denis McMahon, denismfmcmahon at gmail.com



More information about the Python-list mailing list