Optional parameter object re-used when instantiating multiple objects

Arnaud Delobelle arnodel at googlemail.com
Sun Nov 16 02:05:51 EST 2008


Steven D'Aprano <steve at REMOVE-THIS-cybersource.com.au> writes:

> On Sat, 15 Nov 2008 01:40:04 -0800, Rick Giuly wrote:
>
>> Hello All,
>> 
>> Why is python designed so that b and c (according to code below)
>> actually share the same list object? It seems more natural to me that
>> each object would be created with a new list object in the points
>> variable.
>
> That's not natural *at all*. You're initialising the argument "points" 
> with the same list every time. If you wanted it to have a different list 
> each time, you should have said so. Don't blame the language for doing 
> exactly what you told it to do.

Come on.  The fact that this questions comes up so often (twice in 24h)
is proof that this is a surprising behaviour.  I do think it is the
correct one but it is very natural to assume that when you write

    def foo(bar=[]):
         bar.append(6)
         ...

you are describing what happens when you _call_ foo, i.e.:

    1. if bar is not provided, make it equal to []
    2. Append 6 to bar
    3. ...

-- 
Arnaud



More information about the Python-list mailing list