default method parameter behavior

Konstantin Veretennicov kveretennicov at gmail.com
Wed Apr 2 22:36:30 CEST 2008


On Wed, Apr 2, 2008 at 10:59 PM, <jianbing.chen at gmail.com> wrote:
> 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



More information about the Python-list mailing list