Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #69624
| From | Dennis Lee Bieber <wlfraed@ix.netcom.com> |
|---|---|
| Subject | Re: Default mutable parameters in functions |
| Date | 2014-04-03 20:27 -0400 |
| Organization | IISS Elusive Unicorn |
| References | <ac388f0b-8951-42af-a94f-33abdb7231e7@googlegroups.com> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.8869.1396571282.18130.python-list@python.org> (permalink) |
On Thu, 3 Apr 2014 11:49:56 -0700 (PDT), fbicknel@gmail.com declaimed the
following:
>But mutables behave very strangely (imho). Take this example:
>
No, they don't...
<snip>
>it picks up where it left off.
>
As it should...
>I was rather expecting it to start with 4!
>>> def foo(bar = [42]):
... print "I'm %s with %s" % (id(bar), bar[0])
... bar[0] += 1
...
>>> foo()
I'm 70238984 with 42
>>> foo()
I'm 70238984 with 43
>>> foo()
I'm 70238984 with 44
>>> foo([3])
I'm 70242184 with 3
>>> foo([3])
I'm 70668424 with 3
>>> foo()
I'm 70238984 with 45
>>>
The default was evaluated once -- it is a list with ID 70238984 (in
this case), and that ID will not change regardless of what goes on inside
the list.
When called with [3], the function acts on a different list created
just for that call (since it was a list literal).
--
Wulfraed Dennis Lee Bieber AF6VN
wlfraed@ix.netcom.com HTTP://wlfraed.home.netcom.com/
Back to comp.lang.python | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread
Default mutable parameters in functions fbicknel@gmail.com - 2014-04-03 11:49 -0700
Re: Default mutable parameters in functions Ian Kelly <ian.g.kelly@gmail.com> - 2014-04-03 15:32 -0600
Re: Default mutable parameters in functions Ethan Furman <ethan@stoneleaf.us> - 2014-04-03 14:44 -0700
Re: Default mutable parameters in functions Dennis Lee Bieber <wlfraed@ix.netcom.com> - 2014-04-03 20:27 -0400
Re: Default mutable parameters in functions Mark Lawrence <breamoreboy@yahoo.co.uk> - 2014-04-04 01:38 +0100
Re: Default mutable parameters in functions random832@fastmail.us - 2014-04-04 10:00 -0400
Re: Default mutable parameters in functions Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2014-04-04 14:34 +0000
Re: Default mutable parameters in functions Chris Angelico <rosuav@gmail.com> - 2014-04-05 09:47 +1100
Re: Default mutable parameters in functions Dennis Lee Bieber <wlfraed@ix.netcom.com> - 2014-04-04 19:23 -0400
Re: Default mutable parameters in functions Roy Smith <roy@panix.com> - 2014-04-04 19:38 -0400
Re: Default mutable parameters in functions Dave Angel <davea@davea.name> - 2014-04-04 22:21 -0400
csiph-web