e-mail address change (was Re: [Tutor] python's default argument value handling in functions - weird syntax? problem grappling with the concept)

Max Noel maxnoel_fr at yahoo.fr
Thu Feb 10 04:26:06 CET 2005


On Feb 10, 2005, at 03:07, Ismael Garrido wrote:

> Danny Yoo wrote:
>
>> ###
>>
>> def f(a,L=[]):
>>    if L==[5]:
>>        print 'L==[5] caught'
>>        print L
>>        print 'resetting L...'
>>        L=[]
>>    L.append(a)
>>    return L
>>
>> ###
>>
> Now I'm dizzy... I can't understand why there are two "L"!
> L is a local variable of the function, right? (I can't imagine it 
> being anything else) Then if I reassign L to something, why doesn't it 
> keep that change till next run? At least, it keeps the values in the 
> list.. so it should keep the reassignation, no?
> I'm completly puzzled :-S

	It's not L you have to look at but the default value itself. L is 
local to the function and recreated each time you run it. The default 
value, however (which has no name, so I'm gonna call it "defVal"), is 
static (in the Java/C++ sense of the word -- it's only created once). 
The first time you run the function, defVal is set to [] and then it is 
assigned to L (as in, L = defVal).
	Since defVal is a list, L and defVal are actually two names for the 
same variable. Thus, when you append something to L, it is appended to 
defVal as well. However, when you do L = [], you're binding the name L 
to another variable (which you create on the spot). But the name defVal 
is still bound to the same variable! Thus, when you run the function 
again, you get defVal as you left it.

# Let's consider that defVal == [5] (say, you've already called f(5)) 
and call f(10):
if L == [5]:		# L == defVal == [5] (they are the same variable)
	L = []		# Re-binding the name: a new var is created. L == []; defVal 
== [5]
L.append(a)		# L == [10]; defVal == [5].

	See what I mean?

-- Max
maxnoel_fr at yahoo dot fr -- ICQ #85274019
"Look at you hacker... A pathetic creature of meat and bone, panting 
and sweating as you run through my corridors... How can you challenge a 
perfect, immortal machine?"



More information about the Tutor mailing list