Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #8478
| Subject | Re: Default value for optional parameters unexpected behaviour? |
|---|---|
| From | Corey Richardson <kb1pkl@aim.com> |
| References | <2a25a54a-c60b-4811-9c6a-97c7f717dccb@hd10g2000vbb.googlegroups.com> |
| Date | 2011-06-26 14:36 -0400 |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.426.1309113702.1164.python-list@python.org> (permalink) |
[Multipart message — attachments visible in raw view] - view raw
Excerpts from Marc Aymerich's message of Sun Jun 26 14:28:30 -0400 2011:
> Hi,
> I'm trying to define a function that has an optional parameter which
> should be an empty list whenever it isn't given. However, it takes as
> value the same value as the last time the function was executed. What
> is the reason of this behaviour? How does python deal with default
> values (i.e. when are they assigned/created)?
>
> Thanks :)
>
Really common mistake, I made it myself too. When Python evaluates the
function, it sees the default parameter of `foo' as the new object you
create with []. It keeps that object around. The proper idiom instead of
> >>> def a(foo=[]):
> ... foo.append(1)
> ... print foo
> ...
is
def a(foo=None):
if foo is None:
foo = []
foo.append(1)
print foo
--
Corey Richardson
"Those who deny freedom to others, deserve it not for themselves"
-- Abraham Lincoln
Back to comp.lang.python | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread
Default value for optional parameters unexpected behaviour? Marc Aymerich <glicerinu@gmail.com> - 2011-06-26 11:28 -0700 Re: Default value for optional parameters unexpected behaviour? Shashank Singh <shashank.sunny.singh@gmail.com> - 2011-06-27 00:09 +0530 Re: Default value for optional parameters unexpected behaviour? Corey Richardson <kb1pkl@aim.com> - 2011-06-26 14:36 -0400 Re: Default value for optional parameters unexpected behaviour? Noah Hall <enalicho@gmail.com> - 2011-06-26 19:45 +0100 Re: Default value for optional parameters unexpected behaviour? Terry Reedy <tjreedy@udel.edu> - 2011-06-26 14:46 -0400 Re: Default value for optional parameters unexpected behaviour? Benjamin Kaplan <benjamin.kaplan@case.edu> - 2011-06-26 12:21 -0700 Re: Default value for optional parameters unexpected behaviour? Corey Richardson <kb1pkl@aim.com> - 2011-06-26 15:23 -0400
csiph-web