By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
438,216 Members | 1,001 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 438,216 IT Pros & Developers. It's quick & easy.

default method parameter behavior

P: n/a
I ran into a similar situation like the following (ipython session).
Can anyone please explain why the behavior?
Thanks in advance.

In [11]: def foo(b=[]):
....: b.append(3)
....: return b
....:

In [12]: foo()
Out[12]: [3]

In [13]: foo()
Out[13]: [3, 3]

In [14]: foo([])
Out[14]: [3]

In [15]: foo([])
Out[15]: [3]
Apr 2 '08 #1
Share this Question
Share on Google+
2 Replies


P: n/a
On Wed, Apr 2, 2008 at 10:59 PM, <ji***********@gmail.comwrote:
I ran into a similar situation like the following (ipython session).
Can anyone please explain why the behavior?
Of course.
>From http://docs.python.org/ref/function.html:
Default parameter values are evaluated when the function definition is
executed. This means that the expression is evaluated once, when the
function is defined, and that that same ``pre-computed'' value is used
for each call. This is especially important to understand when a
default parameter is a mutable object, such as a list or a dictionary:
if the function modifies the object (e.g. by appending an item to a
list), the default value is in effect modified.

--
kv
Apr 2 '08 #2

P: n/a
On Wed, Apr 2, 2008 at 3:59 PM, <ji***********@gmail.comwrote:
I ran into a similar situation like the following (ipython session).
Can anyone please explain why the behavior?
http://www.python.org/doc/faq/genera...etween-objects

Since you got bitten by this, you may also find it useful to take a
look at one of the pages that talks about common python problems, like
http://zephyrfalcon.org/labs/python_pitfalls.html or
http://www.ferg.org/projects/python_gotchas.html (both of which
mention the problems with mutable default arguments).

--
Jerry
Apr 2 '08 #3

This discussion thread is closed

Replies have been disabled for this discussion.