Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #64449
| References | <52dec646$0$2934$426a74cc@news.free.fr> <mailman.5813.1390331956.18130.python-list@python.org> <52decc31$0$2244$426a74cc@news.free.fr> |
|---|---|
| Date | 2014-01-22 06:46 +1100 |
| Subject | Re: Modifying the default argument of function |
| From | Chris Angelico <rosuav@gmail.com> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.5816.1390333586.18130.python-list@python.org> (permalink) |
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
Back to comp.lang.python | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll 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