[Tutor] newbie question about default arguments
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:
>>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==:
>> print "id(L2) =", id(L)
>> return L
> Tutor maillist - Tutor at python.org
More information about the Tutor