Modifying the default argument of function

Chris Angelico rosuav at gmail.com
Tue Jan 21 14:19:12 EST 2014


On Wed, Jan 22, 2014 at 6:11 AM, Mû <mu-- at melix.net> wrote:
> The function acts as if there were a global variable x, but the call of x
> results in an error (undefined variable). I don't understand why the
> successive calls of f() don't return the same value: indeed, I thought that
> [2,3] was the default argument of the function f, thus I expected the three
> calls of f() to be exactly equivalent.

In a sense, there is. The default for the argument is simply an object
like any other, and it's stored in one place.

For cases where you want a mutable default that is "reset" every time,
the most common idiom is this:

def f(x=None):
    if x is None: x=[2,3]
    x.append(1)
    return x

That will create a new list every time, with the same initial contents.

ChrisA



More information about the Python-list mailing list