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


Groups > comp.lang.python > #64468

Re: Modifying the default argument of function

Newsgroups comp.lang.python
Date 2014-01-21 16:30 -0800
References <52dec646$0$2934$426a74cc@news.free.fr> <mailman.5813.1390331956.18130.python-list@python.org> <52decc31$0$2244$426a74cc@news.free.fr> <mailman.5816.1390333586.18130.python-list@python.org>
Message-ID <5e78b144-5e3d-48c2-adb1-df64878b8bf2@googlegroups.com> (permalink)
Subject Re: Modifying the default argument of function
From Asaf Las <roegltd@gmail.com>

Show all headers | View raw


On Tuesday, January 21, 2014 9:46:16 PM UTC+2, Chris Angelico wrote:
> On Wed, Jan 22, 2014 at 6:36 AM, Mû <mu--@melix.net> wrote:
> > These were clear and quick answers to my problem. I did not think of this
> > possibility: the default argument is created once, but accessible only by
> > the function, therefore is not a global variable, whereas it looks like if
> > it were at first glance.
> You can actually poke at the function a bit and see what's happening.
> Try this in the interactive interpreter:
> >>> def f(x=[2,3]):
>     x.append(1)
>     return x
> >>> f()
> [2, 3, 1]
> >>> f()
> [2, 3, 1, 1]
> >>> f.__defaults__
> ([2, 3, 1, 1],)
> 
> The __defaults__ attribute of a function is a tuple of its parameter
> defaults. You can easily see there that the list has changed as you
> changed it in the function. You could check it with id() or is, too:
> >>> id(f.__defaults__[0])
> 24529576
> >>> id(f())
> 24529576
> >>> f() is f.__defaults__[0]
> True
> ChrisA

that reminds me C's static :-)

def func(y, x = [1]):
    if y != 1 :
        func.__defaults__[0][0] = y
    print(func.__defaults__[0])

func(0)
func(2)
func(1)

[0]
[2]
[2]

p.s. Mu, thanks for question!

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