[Tutor] newbie question about default arguments
Kent Johnson
kent37 at tds.net
Wed Mar 29 20:49:24 CEST 2006
Josh Adams wrote:
> Thanks for your help. That makes a lot more sense.
>
> Not to ask too many stupid questions, but why does the L2 assignment in the
> if-block create a new L variable? Shouldn't the scope from the function
> definition dominate the inner scope of the if-block?
It doesn't create a new variable, it binds a new value to the name L. if
statements don't introduce a new scope so you are right about that.
Default values for functions are evaluated just once, when the function
is defined. Rebinding L to a new list inside the function makes each
execution get a fresh list.
This might help you understand Python name-binding semantics:
http://effbot.org/zone/python-objects.htm
Kent
>
> Thanks,
> Josh
>
>
>>Josh,
>>
>>If you print the id() of your L inside your f2(), you will notice something..
>>In short, the default value stays the same; what you modified was another
>>copy of []. Hope it helps.
>>
>>def f2(a, L=[]):
>> print "id(L) = ", id(L)
>> if L==[]:
>> L=[]
>> print "id(L2) =", id(L)
>> L.append(a)
>> return L
>>
>>
>>>>>print f2(1)
>>
>>id(L)= 11788336
>>id(L2)= 12047184
>>[1]
>>
>>Kenny
>>
>>
>
>
>
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
More information about the Tutor
mailing list