Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #64444

Re: Modifying the default argument of function

References <52dec646$0$2934$426a74cc@news.free.fr>
Date 2014-01-22 06:19 +1100
Subject Re: Modifying the default argument of function
From Chris Angelico <rosuav@gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.5813.1390331956.18130.python-list@python.org> (permalink)

Show all headers | View raw


On Wed, Jan 22, 2014 at 6:11 AM, Mû <mu--@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

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

Modifying the default argument of function Mû <mu--@melix.net> - 2014-01-21 20:11 +0100
  Re: Modifying the default argument of function Chris Angelico <rosuav@gmail.com> - 2014-01-22 06:19 +1100
    Re: Modifying the default argument of function Mû <mu--@melix.net> - 2014-01-21 20:36 +0100
      Re: Modifying the default argument of function Chris Angelico <rosuav@gmail.com> - 2014-01-22 06:46 +1100
        Re: Modifying the default argument of function Asaf Las <roegltd@gmail.com> - 2014-01-21 16:30 -0800
  Re: Modifying the default argument of function Steve Jones <steve@secretvolcanobase.org> - 2014-01-21 19:19 +0000
  Re: Modifying the default argument of function emile <emile@fenx.com> - 2014-01-21 11:20 -0800

csiph-web