bug ???

Robin Munn rmunn at pobox.com
Sat Mar 29 18:43:34 EST 2003


Franck Bui-Huu <Franck.BUI-HUU at gemplus.com> wrote:
> Hey
> 
> I don't understand a weird behavior of python
> 
> I ve got two functions:
> 
> def function1(var1, var2):
>      ...
>      function2(var1, var2) # first call to function2
>      function2(var1, var2) # second call to function2
> 
> def function2(var1, var2, var3 = []):
>      .....
> 
> At the start of function2 during its first call var3 = [] -> OK
> but during the second call (always at its starting) var3 = [97,3] which is
> the value of var3 when first call of function2 was ending ???
> 
> if I call function2 by : function2(var1, var2, []) all works fine....
> 
> Anyone can help me ?

You probably haven't gotten a response yet because so many people have
been away at PyCon 2003...

Basically, when the "def function2" line is executed, function2 is
defined. In the same line, an empty list object is created and set as
the default parameter to var3. Then in the body of function2, you modify
that list object -- so the first time you call function2 without a third
parameter, the default parameter (a list object that is currently empty)
is assigned to var3. During execution of function2, that list object is
modified. Then the second time function2 is called with no third
parameter, that same list object (no longer empty) is assigned to var3
as its default parameter.

What you actually wanted to do was something like this:

def function2(var1, var2, var3 = None):
    if var3 is None:
        var3 = []
    # Rest of function2 here...

Read http://www.python.org/doc/FAQ.html#6.25 for more information.

P.S. Notice the distinction I'm making between *names* and *objects*. If
you're coming to Python from a language like C, you may not be used to
this distinction -- but once you grok that names are just pointers to
objects, several things that used to be confusing may start to make more
sense.

-- 
Robin Munn <rmunn at pobox.com>
http://www.rmunn.com/
PGP key ID: 0x6AFB6838    50FF 2478 CFFB 081A 8338  54F7 845D ACFD 6AFB 6838




More information about the Python-list mailing list